/*---------------------------------------------------------------------------*/ void LuaUtils_CheckParameter1(lua_State *L, uint16_t count, const char* usage) { int n = lua_gettop(L); if (n != count) luaL_error(L, "Got %d arguments expected %d (%s)", n, count, usage); }
/* * success,err = statement:execute(...) */ static int statement_execute(lua_State *L) { int n = lua_gettop(L); statement_t *statement = (statement_t *)luaL_checkudata(L, 1, DBD_MYSQL_STATEMENT); int num_bind_params = n - 1; int expected_params; unsigned char *buffer = NULL; int offset = 0; MYSQL_BIND *bind = NULL; MYSQL_RES *metadata = NULL; char *error_message = NULL; char *errstr = NULL; int p; if (statement->metadata) { /* * free existing metadata from any previous executions */ mysql_free_result(statement->metadata); statement->metadata = NULL; } if (!statement->stmt) { lua_pushboolean(L, 0); lua_pushstring(L, DBI_ERR_EXECUTE_INVALID); return 2; } expected_params = mysql_stmt_param_count(statement->stmt); if (expected_params != num_bind_params) { /* * mysql_stmt_bind_param does not handle this condition, * and the client library will segfault if these do no match */ lua_pushboolean(L, 0); lua_pushfstring(L, DBI_ERR_PARAM_MISCOUNT, expected_params, num_bind_params); return 2; } if (num_bind_params > 0) { bind = malloc(sizeof(MYSQL_BIND) * num_bind_params); if (bind == NULL) { luaL_error(L, "Could not alloc bind params\n"); } buffer = (unsigned char *)malloc(num_bind_params * sizeof(double)); memset(bind, 0, sizeof(MYSQL_BIND) * num_bind_params); } for (p = 2; p <= n; p++) { int type = lua_type(L, p); int i = p - 2; const char *str = NULL; size_t *str_len = NULL; double *num = NULL; int *boolean = NULL; char err[64]; switch(type) { case LUA_TNIL: bind[i].buffer_type = MYSQL_TYPE_NULL; bind[i].is_null = (my_bool*)1; break; case LUA_TBOOLEAN: boolean = (int *)(buffer + offset); offset += sizeof(int); *boolean = lua_toboolean(L, p); bind[i].buffer_type = MYSQL_TYPE_LONG; bind[i].is_null = (my_bool*)0; bind[i].buffer = (char *)boolean; bind[i].length = 0; break; case LUA_TNUMBER: /* * num needs to be it's own * memory here */ num = (double *)(buffer + offset); offset += sizeof(double); *num = lua_tonumber(L, p); bind[i].buffer_type = MYSQL_TYPE_DOUBLE; bind[i].is_null = (my_bool*)0; bind[i].buffer = (char *)num; bind[i].length = 0; break; case LUA_TSTRING: str_len = (size_t *)(buffer + offset); offset += sizeof(size_t); str = lua_tolstring(L, p, str_len); bind[i].buffer_type = MYSQL_TYPE_STRING; bind[i].is_null = (my_bool*)0; bind[i].buffer = (char *)str; bind[i].length = str_len; break; default: snprintf(err, sizeof(err)-1, DBI_ERR_BINDING_TYPE_ERR, lua_typename(L, type)); errstr = err; error_message = DBI_ERR_BINDING_PARAMS; goto cleanup; } } if (mysql_stmt_bind_param(statement->stmt, bind)) { error_message = DBI_ERR_BINDING_PARAMS; goto cleanup; } if (mysql_stmt_execute(statement->stmt)) { error_message = DBI_ERR_BINDING_EXEC; goto cleanup; } metadata = mysql_stmt_result_metadata(statement->stmt); if (metadata) { mysql_stmt_store_result(statement->stmt); } cleanup: if (bind) { free(bind); } if (buffer) { free(buffer); } if (error_message) { lua_pushboolean(L, 0); lua_pushfstring(L, error_message, errstr ? errstr : mysql_stmt_error(statement->stmt)); return 2; } statement->metadata = metadata; lua_pushboolean(L, 1); return 1; }
static void loaderror(lua_State *L, const char *filename) { luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s", lua_tostring(L, 1), filename, lua_tostring(L, -1)); }
static int str_format (lua_State *L) { int top = lua_gettop(L); int arg = 1; size_t sfl; const char *strfrmt = luaL_checklstring(L, arg, &sfl); const char *strfrmt_end = strfrmt+sfl; luaL_Buffer b; luaL_buffinit(L, &b); while (strfrmt < strfrmt_end) { if (*strfrmt != L_ESC) luaL_addchar(&b, *strfrmt++); else if (*++strfrmt == L_ESC) luaL_addchar(&b, *strfrmt++); /* %% */ else { /* format item */ char form[MAX_FORMAT]; /* to store the format (`%...') */ char buff[MAX_ITEM]; /* to store the formatted item */ if (++arg > top) luaL_argerror(L, arg, "no value"); strfrmt = scanformat(L, strfrmt, form); switch (*strfrmt++) { case 'c': { sprintf(buff, form, (int)luaL_checknumber(L, arg)); break; } case 'd': case 'i': { addintlen(form); sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg)); break; } case 'o': case 'u': case 'x': case 'X': { addintlen(form); sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg)); break; } case 'e': case 'E': case 'f': case 'g': case 'G': { sprintf(buff, form, (double)luaL_checknumber(L, arg)); break; } case 'q': { addquoted(L, &b, arg); continue; /* skip the 'addsize' at the end */ } case 's': { size_t l; const char *s = luaL_checklstring(L, arg, &l); if (!strchr(form, '.') && l >= 100) { /* no precision and string is too long to be formatted; keep original string */ lua_pushvalue(L, arg); luaL_addvalue(&b); continue; /* skip the `addsize' at the end */ } else { sprintf(buff, form, s); break; } } default: { /* also treat cases `pnLlh' */ return luaL_error(L, "invalid option " LUA_QL("%%%c") " to " LUA_QL("format"), *(strfrmt - 1)); } } luaL_addlstring(&b, buff, strlen(buff)); } } luaL_pushresult(&b); return 1; }
int icu_case(lua_State *L) { size_t input_l; const char* input = luaL_checklstring(L, 1, &input_l); const char* locale = luaL_checkstring(L, 2); const char* recase = luaL_checkstring(L, 3); /* Convert input to ICU-friendly UChars */ UChar *input_as_uchar; int32_t l; utf8_to_uchar(input, input_l, input_as_uchar, l); /* Now do the conversion */ UChar *output; int32_t l2 = 0; UErrorCode err = U_ZERO_ERROR; if (strcmp(recase, "title") == 0) { l2 = u_strToTitle(NULL, 0, input_as_uchar, l, NULL, locale, &err); err = U_ZERO_ERROR; output = malloc(l2 * sizeof(UChar)); u_strToTitle(output, l2, input_as_uchar, l, NULL, locale, &err); } else { conversion_function_t conversion; if (strcmp(recase, "upper") == 0) { conversion = u_strToUpper; } else if (strcmp(recase, "lower") == 0) { conversion = u_strToLower; } else { free(input_as_uchar); return luaL_error(L, "Unknown case conversion type %s", recase); } l2 = conversion(NULL, 0, input_as_uchar, l, locale, &err); err = U_ZERO_ERROR; output = malloc(l2 * sizeof(UChar)); conversion(output, l2, input_as_uchar, l, locale, &err); } if (!U_SUCCESS(err)) { free(input_as_uchar); free(output); return luaL_error(L, "Error in case conversion %s", u_errorName(err)); } int32_t l3 = 0; char possibleOutbuf[4096]; u_strToUTF8(possibleOutbuf, 4096, &l3, output, l2, &err); if (U_SUCCESS(err)) { lua_pushstring(L, possibleOutbuf); free(input_as_uchar); free(output); return 1; } char *utf8output; if (err == U_BUFFER_OVERFLOW_ERROR) { utf8output = malloc(l3); u_strToUTF8(utf8output, l3, NULL, output, l2, &err); if (!U_SUCCESS(err)) goto fail; utf8output[l3] = '\0'; lua_pushstring(L, utf8output); free(input_as_uchar); free(output); free(utf8output); return 1; } fail: return luaL_error(L, "Error in UTF8 conversion %s", u_errorName(err)); }
static int check_capture (MatchState *ms, int l) { l -= '1'; if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED) return luaL_error(ms->L, "invalid capture index"); return l; }
static const char *match (MatchState *ms, const char *s, const char *p) { init: /* using goto's to optimize tail recursion */ switch (*p) { case '(': { /* start capture */ if (*(p+1) == ')') /* position capture? */ return start_capture(ms, s, p+2, CAP_POSITION); else return start_capture(ms, s, p+1, CAP_UNFINISHED); } case ')': { /* end capture */ return end_capture(ms, s, p+1); } case L_ESC: { switch (*(p+1)) { case 'b': { /* balanced string? */ s = matchbalance(ms, s, p+2); if (s == NULL) return NULL; p+=4; goto init; /* else return match(ms, s, p+4); */ } case 'f': { /* frontier? */ const char *ep; char previous; p += 2; if (*p != '[') luaL_error(ms->L, "missing " LUA_QL("[") " after " LUA_QL("%%f") " in pattern"); ep = classend(ms, p); /* points to what is next */ previous = (s == ms->src_init) ? '\0' : *(s-1); if (matchbracketclass(uchar(previous), p, ep-1) || !matchbracketclass(uchar(*s), p, ep-1)) return NULL; p=ep; goto init; /* else return match(ms, s, ep); */ } default: { if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */ s = match_capture(ms, s, uchar(*(p+1))); if (s == NULL) return NULL; p+=2; goto init; /* else return match(ms, s, p+2) */ } goto dflt; /* case default */ } } } case '\0': { /* end of pattern */ return s; /* match succeeded */ } case '$': { if (*(p+1) == '\0') /* is the `$' the last char in pattern? */ return (s == ms->src_end) ? s : NULL; /* check end of string */ else goto dflt; } default: dflt: { /* it is a pattern item */ const char *ep = classend(ms, p); /* points to what is next */ int m = s<ms->src_end && singlematch(uchar(*s), p, ep); switch (*ep) { case '?': { /* optional */ const char *res; if (m && ((res=match(ms, s+1, ep+1)) != NULL)) return res; p=ep+1; goto init; /* else return match(ms, s, ep+1); */ } case '*': { /* 0 or more repetitions */ return max_expand(ms, s, p, ep); } case '+': { /* 1 or more repetitions */ return (m ? max_expand(ms, s+1, p, ep) : NULL); } case '-': { /* 0 or more repetitions (minimum) */ return min_expand(ms, s, p, ep); } default: { if (!m) return NULL; s++; p=ep; goto init; /* else return match(ms, s+1, ep); */ } } } } }
static int rjson_parse_message(lua_State *lua) { lua_getfield(lua, LUA_REGISTRYINDEX, LSB_HEKA_THIS_PTR); lsb_heka_sandbox *hsb = static_cast<lsb_heka_sandbox *>(lua_touserdata(lua, -1)); lua_pop(lua, 1); // remove this ptr if (!hsb) { return luaL_error(lua, "parse_message() invalid " LSB_HEKA_THIS_PTR); } int n = lua_gettop(lua); int idx = 1; const lsb_heka_message *msg = NULL; if (lsb_heka_get_type(hsb) == 'i') { luaL_argcheck(lua, n >= 2 && n <= 4, 0, "invalid number of arguments"); heka_stream_reader *hsr = static_cast<heka_stream_reader *> (luaL_checkudata(lua, 1, LSB_HEKA_STREAM_READER)); msg = &hsr->msg; idx = 2; } else { luaL_argcheck(lua, n >= 1 && n <= 3, 0, "invalid number of arguments"); const lsb_heka_message *hm = lsb_heka_get_message(hsb); if (!hm || !hm->raw.s) { return luaL_error(lua, "parse_message() no active message"); } msg = hm; } lsb_const_string json = read_message(lua, idx, msg); if (!json.s) return luaL_error(lua, "field not found"); char *inflated = NULL; #ifdef HAVE_ZLIB // automatically handle gzipped strings (optimization for Mozilla telemetry // messages) if (json.len > 2) { if (json.s[0] == 0x1f && (unsigned char)json.s[1] == 0x8b) { size_t mms = (size_t)lua_tointeger(lua, lua_upvalueindex(1)); inflated = ungzip(json.s, json.len, mms, NULL); if (!inflated) return luaL_error(lua, "ungzip failed"); } } #endif rjson *j = static_cast<rjson *>(lua_newuserdata(lua, sizeof*j)); j->doc = new rj::Document; j->val = NULL; j->insitu = inflated; j->refs = new std::set<rj::Value *>; luaL_getmetatable(lua, mozsvc_rjson); lua_setmetatable(lua, -2); if (!j->doc || !j->refs) { lua_pushstring(lua, "memory allocation failed"); return lua_error(lua); } bool err = false; if (j->insitu) { if (j->doc->ParseInsitu<rj::kParseStopWhenDoneFlag>(j->insitu) .HasParseError()) { err = true; lua_pushfstring(lua, "failed to parse offset:%f %s", (lua_Number)j->doc->GetErrorOffset(), rj::GetParseError_En(j->doc->GetParseError())); } } else { rj::MemoryStream ms(json.s, json.len); if (j->doc->ParseStream<0, rj::UTF8<> >(ms).HasParseError()) { err = true; lua_pushfstring(lua, "failed to parse offset:%f %s", (lua_Number)j->doc->GetErrorOffset(), rj::GetParseError_En(j->doc->GetParseError())); } } if (err) return lua_error(lua); j->refs->insert(j->doc); return 1; }
static size_t dump_writer(void *ud, const char *s, size_t len) { lonL_Dumper *D = (lonL_Dumper*)ud; if (!lon_addlstring(&D->B, s, len)) luaL_error(D->L, "out of memory"); return len; }
int luax_assert_function(lua_State *L, int n) { if (!lua_isfunction(L, n)) return luaL_error(L, "Argument must be of type \"function\"."); return 0; }
static int str_format (lua_State *L) { int top = lua_gettop(L); int arg = 1; size_t sfl; const char *strfrmt = luaL_checklstring(L, arg, &sfl); const char *strfrmt_end = strfrmt+sfl; luaL_Buffer b; luaL_buffinit(L, &b); while (strfrmt < strfrmt_end) { if (*strfrmt != L_ESC) luaL_addchar(&b, *strfrmt++); else if (*++strfrmt == L_ESC) luaL_addchar(&b, *strfrmt++); /* %% */ else { /* format item */ char form[MAX_FORMAT]; /* to store the format (`%...') */ char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */ int nb = 0; /* number of bytes in added item */ if (++arg > top) luaL_argerror(L, arg, "no value"); strfrmt = scanformat(L, strfrmt, form); switch (*strfrmt++) { case 'c': { nb = sprintf(buff, form, luaL_checkint(L, arg)); break; } case 'd': case 'i': { lua_Number n = luaL_checknumber(L, arg); luaL_argcheck(L, (MIN_INTFRM - 1) < n && n < (MAX_INTFRM + 1), arg, "not a number in proper range"); addlenmod(form, LUA_INTFRMLEN); nb = sprintf(buff, form, (LUA_INTFRM_T)n); break; } case 'o': case 'u': case 'x': case 'X': { lua_Number n = luaL_checknumber(L, arg); luaL_argcheck(L, 0 <= n && n < (MAX_UINTFRM + 1), arg, "not a non-negative number in proper range"); addlenmod(form, LUA_INTFRMLEN); nb = sprintf(buff, form, (unsigned LUA_INTFRM_T)n); break; } case 'e': case 'E': case 'f': #if defined(LUA_USE_AFORMAT) case 'a': case 'A': #endif case 'g': case 'G': { addlenmod(form, LUA_FLTFRMLEN); nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg)); break; } case 'q': { addquoted(L, &b, arg); break; } case 's': { size_t l; const char *s = luaL_tolstring(L, arg, &l); if (!strchr(form, '.') && l >= 100) { /* no precision and string is too long to be formatted; keep original string */ luaL_addvalue(&b); break; } else { nb = sprintf(buff, form, s); lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ break; } } default: { /* also treat cases `pnLlh' */ return luaL_error(L, "invalid option " LUA_QL("%%%c") " to " LUA_QL("format"), *(strfrmt - 1)); } } luaL_addsize(&b, nb); } } luaL_pushresult(&b); return 1; }
static int luaB_assert (lua_State *L) { luaL_checkany(L, 1); if (!lua_toboolean(L, 1)) return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!")); return lua_gettop(L); }
LUA_API int luafan_objectbuf_decode(lua_State *L) { size_t len; const char *buf = luaL_checklstring(L, 1, &len); BYTEARRAY input; bytearray_wrap_buffer(&input, (uint8_t *)buf, len); // will not change buf. int sym_idx = 0; if (lua_istable(L, 2)) { sym_idx = 2; } uint8_t flag = 0; bytearray_read8(&input, &flag); switch (flag) { case 0: lua_pushboolean(L, false); return 1; case 1: lua_pushboolean(L, true); return 1; default: break; } lua_newtable(L); int index_map_idx = lua_gettop(L); uint32_t index = 2; if (!sym_idx) { lua_newtable(L); } else { lua_rawgeti(L, sym_idx, SYM_INDEX_INDEX); index = lua_tointeger(L, -1); lua_pop(L, 1); lua_rawgeti(L, sym_idx, SYM_INDEX_MAP_VK); } int sym_map_vk_idx = lua_gettop(L); int last_top = index + 1; if (!sym_idx) { lua_pushboolean(L, false); lua_rawseti(L, index_map_idx, FALSE_INDEX); lua_pushboolean(L, true); lua_rawseti(L, index_map_idx, TRUE_INDEX); } if (flag & HAS_NUMBER_MASK) { last_top = index + 1; uint32_t count = 0; if (!ffi_stream_get_u30(&input, &count)) { lua_pushnil(L); lua_pushliteral(L, "decode failed, can't get `number` count."); return 2; } uint32_t i = 1; for (; i <= count; i++) { double result = 0; if (!ffi_stream_get_d64(&input, &result)) { lua_pushnil(L); lua_pushfstring(L, "decode failed, can't decode `number`, %d/%d", i, count); return 2; } lua_pushnumber(L, result); lua_rawseti(L, index_map_idx, ++index); } } if (flag & HAS_U30_MASK) { last_top = index + 1; uint32_t count = 0; if (!ffi_stream_get_u30(&input, &count)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } uint32_t i = 1; for (; i <= count; i++) { uint32_t count = 0; if (!ffi_stream_get_u30(&input, &count)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } lua_pushinteger(L, count); lua_rawseti(L, index_map_idx, ++index); } } if (flag & HAS_STRING_MASK) { last_top = index + 1; uint32_t count = 0; if (!ffi_stream_get_u30(&input, &count)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } uint32_t i = 1; for (; i <= count; i++) { uint8_t *buff = NULL; size_t buflen = 0; ffi_stream_get_string(&input, &buff, &buflen); if (!buff) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } lua_pushlstring(L, (const char *)buff, buflen); lua_rawseti(L, index_map_idx, ++index); } } if (flag & HAS_TABLE_MASK) { last_top = index + 1; uint32_t count = 0; if (!ffi_stream_get_u30(&input, &count)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } uint32_t i = 1; for (; i <= count; i++) { lua_newtable(L); lua_rawseti(L, index_map_idx, index + i); } i = 1; for (; i <= count; i++) { uint8_t *buff = NULL; size_t buflen = 0; ffi_stream_get_string(&input, &buff, &buflen); if (!buff) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } BYTEARRAY d = {0}; bytearray_wrap_buffer(&d, buff, buflen); lua_rawgeti(L, index_map_idx, index + i); while (bytearray_read_available(&d) > 0) { uint32_t ki = 0; if (!ffi_stream_get_u30(&d, &ki)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } uint32_t vi = 0; if (!ffi_stream_get_u30(&d, &vi)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } lua_rawgeti(L, sym_map_vk_idx, ki); if (lua_isnil(L, -1)) { lua_pop(L, 1); lua_rawgeti(L, index_map_idx, ki); if (lua_isnil(L, -1)) { luaL_error(L, "ki=%d not found.", ki); } } lua_rawgeti(L, sym_map_vk_idx, vi); if (lua_isnil(L, -1)) { lua_pop(L, 1); lua_rawgeti(L, index_map_idx, vi); if (lua_isnil(L, -1)) { luaL_error(L, "vi=%d not found.", vi); } } lua_rawset(L, -3); } lua_pop(L, 1); } } lua_rawgeti(L, sym_map_vk_idx, last_top); if (lua_isnil(L, -1)) { lua_rawgeti(L, index_map_idx, last_top); } // return sym_map_vk[last_top] or index_map[last_top] // lua_pushvalue(L, index_map_idx); // lua_pushinteger(L, last_top); return 1; }
LUA_API int luafan_objectbuf_encode(lua_State *L) { int obj_index = 1; int sym_idx = 0; if (lua_isnoneornil(L, 1)) { luaL_error(L, "no argument."); return 0; } if (lua_istable(L, 2)) { sym_idx = 2; } if (lua_isboolean(L, 1)) { int value = lua_toboolean(L, 1); lua_pushstring(L, value ? "\x01" : "\x00"); return 1; } CTX ctx = {0}; ctx_init(&ctx, L); packer(L, &ctx, obj_index); uint8_t flag = 0; BYTEARRAY bodystream; bytearray_alloc(&bodystream, 64); bytearray_write8(&bodystream, flag); // place holder. lua_newtable(L); int index_map_idx = lua_gettop(L); uint32_t index = 2; if (!sym_idx) { lua_newtable(L); } else { lua_rawgeti(L, sym_idx, SYM_INDEX_INDEX); index = lua_tointeger(L, -1); lua_pop(L, 1); lua_rawgeti(L, sym_idx, SYM_INDEX_MAP); } int sym_map_idx = lua_gettop(L); lua_pushboolean(L, false); lua_pushinteger(L, FALSE_INDEX); lua_rawset(L, index_map_idx); lua_pushboolean(L, true); lua_pushinteger(L, TRUE_INDEX); lua_rawset(L, index_map_idx); // --------------------------------------------------------------------------- if (ctx.number_count > 0) { flag |= HAS_NUMBER_MASK; uint32_t realcount = 0; BYTEARRAY d; bytearray_alloc(&d, 0); lua_rawgeti(L, ctx.index, CTX_INDEX_NUMBERS); int i = 1; for (; i <= ctx.number_count; i++) { lua_rawgeti(L, -1, i); lua_pushvalue(L, -1); lua_rawget(L, sym_map_idx); if (lua_isnil(L, -1)) { lua_pop(L, 1); ffi_stream_add_d64(&d, lua_tonumber(L, -1)); lua_pushinteger(L, index + (++realcount)); lua_rawset(L, index_map_idx); } else { lua_pop(L, 2); // pop sym number idx & number } } lua_pop(L, 1); ffi_stream_add_u30(&bodystream, realcount); bytearray_read_ready(&d); bytearray_writebuffer(&bodystream, d.buffer, d.total); bytearray_dealloc(&d); index += realcount; } // --------------------------------------------------------------------------- if (ctx.u30_count > 0) { flag |= HAS_U30_MASK; uint32_t realcount = 0; BYTEARRAY d; bytearray_alloc(&d, 0); lua_rawgeti(L, ctx.index, CTX_INDEX_U30S); int i = 1; for (; i <= ctx.u30_count; i++) { lua_rawgeti(L, -1, i); lua_pushvalue(L, -1); lua_rawget(L, sym_map_idx); if (lua_isnil(L, -1)) { lua_pop(L, 1); ffi_stream_add_u30(&d, lua_tointeger(L, -1)); lua_pushinteger(L, index + (++realcount)); lua_rawset(L, index_map_idx); } else { lua_pop(L, 2); // pop sym u30 idx & u30 } } lua_pop(L, 1); ffi_stream_add_u30(&bodystream, realcount); bytearray_read_ready(&d); bytearray_writebuffer(&bodystream, d.buffer, d.total); bytearray_dealloc(&d); index += realcount; } // --------------------------------------------------------------------------- if (ctx.string_count > 0) { flag |= HAS_STRING_MASK; uint32_t realcount = 0; BYTEARRAY d; bytearray_alloc(&d, 0); lua_rawgeti(L, ctx.index, CTX_INDEX_STRINGS); int i = 1; for (; i <= ctx.string_count; i++) { lua_rawgeti(L, -1, i); lua_pushvalue(L, -1); lua_rawget(L, sym_map_idx); if (lua_isnil(L, -1)) { lua_pop(L, 1); size_t len; const char *buf = lua_tolstring(L, -1, &len); ffi_stream_add_string(&d, buf, len); lua_pushinteger(L, index + (++realcount)); lua_rawset(L, index_map_idx); } else { lua_pop(L, 2); // pop sym u30 idx & u30 } } lua_pop(L, 1); ffi_stream_add_u30(&bodystream, realcount); bytearray_read_ready(&d); bytearray_writebuffer(&bodystream, d.buffer, d.total); bytearray_dealloc(&d); index += realcount; } // --------------------------------------------------------------------------- if (ctx.table_count) { flag |= HAS_TABLE_MASK; ffi_stream_add_u30(&bodystream, ctx.table_count); lua_rawgeti(L, ctx.index, CTX_INDEX_TABLES); int i = 1; for (; i <= ctx.table_count; i++) { lua_rawgeti(L, -1, i); lua_pushinteger(L, index + i); lua_rawset(L, index_map_idx); } for (i = 1; i <= ctx.table_count; i++) { lua_rawgeti(L, -1, i); int tb_idx = lua_gettop(L); BYTEARRAY d; bytearray_alloc(&d, 0); lua_pushnil(L); while (lua_next(L, tb_idx) != 0) { int value_idx = lua_gettop(L); int key_idx = lua_gettop(L) - 1; // d:AddU30(sym_map[k] or index_map[k]) lua_pushvalue(L, key_idx); lua_rawget(L, sym_map_idx); if (lua_isnil(L, -1)) { lua_pop(L, 1); lua_pushvalue(L, key_idx); lua_rawget(L, index_map_idx); } ffi_stream_add_u30(&d, lua_tointeger(L, -1)); lua_pop(L, 1); // d:AddU30(sym_map[v] or index_map[v]) lua_pushvalue(L, value_idx); lua_rawget(L, sym_map_idx); if (lua_isnil(L, -1)) { lua_pop(L, 1); lua_pushvalue(L, value_idx); lua_rawget(L, index_map_idx); } ffi_stream_add_u30(&d, lua_tointeger(L, -1)); lua_pop(L, 1); lua_pop(L, 1); } lua_pop(L, 1); bytearray_read_ready(&d); ffi_stream_add_string(&bodystream, (const char *)d.buffer, d.total); bytearray_dealloc(&d); } lua_pop(L, 1); } bytearray_read_ready(&bodystream); *((uint8_t *)bodystream.buffer) = flag; lua_pushlstring(L, (const char *)bodystream.buffer, bodystream.total); bytearray_dealloc(&bodystream); return 1; }
int Thermal::help(lua_State* L) { if(lua_gettop(L) == 0) { lua_pushstring(L, "Generates a the random thermal field of a *SpinSystem*"); lua_pushstring(L, "1 *3Vector* or *SpinSystem*, 1 Optional *Random*: System Size and built in RNG"); lua_pushstring(L, ""); //output, empty return 3; } if(lua_istable(L, 1)) { return 0; } if(!lua_iscfunction(L, 1)) { return luaL_error(L, "help expect zero arguments or 1 function."); } lua_CFunction func = lua_tocfunction(L, 1); if(func == l_apply) { lua_pushstring(L, "Generates a the random thermal field of a *SpinSystem*"); lua_pushstring(L, "1 *SpinSystem*, 1 Optional *Random*,: The first argument is the spin system which will receive the field. The second optional argument is a random number generator that is used as a source of random values, if absent then the RNG supplied in the constructor will be used."); lua_pushstring(L, ""); return 3; } if(func == l_scalesite) { lua_pushstring(L, "Scale the thermal field at a site. This allows non-uniform thermal effects over a lattice."); lua_pushstring(L, "1 *3Vector*, 1 Number: The vectors define the lattice sites that will have a scaled thermal effect, the number is the how the thermal field is scaled."); lua_pushstring(L, ""); return 3; } if(func == l_settemp) { lua_pushstring(L, "Sets the base value of the temperature. "); lua_pushstring(L, "1 number: temperature of the system."); lua_pushstring(L, ""); return 3; } if(func == l_gettemp) { lua_pushstring(L, "Gets the base value of the temperature. "); lua_pushstring(L, ""); lua_pushstring(L, "1 number: temperature of the system."); return 3; } if(func == l_getscalearray) { lua_pushstring(L, "Get an array representing the thermal scale at each site. This array is connected to the Operator so changes to the returned array will change the Operator."); lua_pushstring(L, ""); lua_pushstring(L, "1 Array: The thermal scale of the sites."); return 3; } if(func == l_setscalearray) { lua_pushstring(L, "Set an array representing the new thermal scale at each site."); lua_pushstring(L, "1 Array: The thermal scale of the sites."); lua_pushstring(L, ""); return 3; } if(func == l_rng) { lua_pushstring(L, "Get the *Random* number generator supplied at initialization"); lua_pushstring(L, ""); lua_pushstring(L, "1 *Random* or 1 nil: RNG"); return 3; } return SpinOperation::help(L); }
static int lua_new_packet(lua_State *L,int packettype){ int argtype = lua_type(L,1); if(packettype == WPACKET){ if(argtype == LUA_TNUMBER || argtype == LUA_TNIL || argtype == LUA_TNONE){ //参数为数字,构造一个初始大小为len的wpacket size_t len = 0; if(argtype == LUA_TNUMBER) len = size_of_pow2(lua_tointeger(L,1)); if(len < 64) len = 64; lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p)); luaL_getmetatable(L, LUAPACKET_METATABLE); lua_setmetatable(L, -2); p->_packet = (packet_t)wpk_create(len); return 1; }else if(argtype == LUA_TSTRING){ size_t len; char *data = (char*)lua_tolstring(L,1,&len); lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p)); luaL_getmetatable(L, LUAPACKET_METATABLE); lua_setmetatable(L, -2); p->_packet = (packet_t)wpk_create_by_bin((int8_t*)data,len); return 1; }else if(argtype == LUA_TUSERDATA){ lua_packet_t other = lua_getluapacket(L,1); if(!other) return luaL_error(L,"invaild opration for arg1"); if(other->_packet->type == RAWPACKET) return luaL_error(L,"invaild opration for arg1"); lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p)); luaL_getmetatable(L, LUAPACKET_METATABLE); lua_setmetatable(L, -2); p->_packet = make_writepacket(other->_packet);//(packet_t)wpk_copy_create(other->_packet); return 1; }else if(argtype == LUA_TTABLE){ wpacket_t wpk = wpk_create(512); if(0 != lua_pack_table(wpk,L,-1)){ destroy_packet((packet_t)wpk); return luaL_error(L,"table should not hava metatable"); //lua_pushnil(L); }else{ lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p)); luaL_getmetatable(L, LUAPACKET_METATABLE); lua_setmetatable(L, -2); p->_packet = (packet_t)wpk; } return 1; } else return luaL_error(L,"invaild opration for arg1"); }else if(packettype == RAWPACKET){ if(argtype == LUA_TSTRING){ //参数为string,构造一个函数数据data的rawpacket size_t len; char *data = (char*)lua_tolstring(L,1,&len); lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p)); luaL_getmetatable(L, LUAPACKET_METATABLE); lua_setmetatable(L, -2); p->_packet = (packet_t)rawpacket_create2(data,len); return 1; }else if(argtype == LUA_TUSERDATA){ lua_packet_t other = lua_getluapacket(L,1); if(!other) return luaL_error(L,"invaild opration for arg1"); if(other->_packet->type != RAWPACKET) return luaL_error(L,"invaild opration for arg1"); lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p)); luaL_getmetatable(L, LUAPACKET_METATABLE); lua_setmetatable(L, -2); p->_packet = clone_packet(other->_packet); return 1; }else return luaL_error(L,"invaild opration for arg1"); }else if(packettype == RPACKET){ if(argtype == LUA_TUSERDATA){ lua_packet_t other = lua_getluapacket(L,1); if(!other) return luaL_error(L,"invaild opration for arg1"); if(other->_packet->type == RAWPACKET) return luaL_error(L,"invaild opration for arg1"); lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p)); luaL_getmetatable(L, LUAPACKET_METATABLE); lua_setmetatable(L, -2); p->_packet = make_readpacket(other->_packet); return 1; }else return luaL_error(L,"invaild opration for arg1"); }else return luaL_error(L,"invaild packet type"); }
static int laura_do_async_call(lua_State *L) { struct laura_node *lnode = NULL; const char *name; struct aura_buffer *buf; struct aura_object *o; int ret; int callback_ref; TRACE(); /* Sanity */ lnode = lua_fetch_node(L, 1); if (!lnode) { lua_stackdump(L); return aura_typeerror(L, 1, "userdata (node)"); } if (!lua_isstring(L, 2)) { lua_stackdump(L); return aura_typeerror(L, 2, "string (object name)"); } if (!lua_isfunction(L, 3)) { lua_stackdump(L); return aura_typeerror(L, 3, "function (callback)"); } name = lua_tostring(L, 2); o = aura_etable_find(lnode->node->tbl, name); if (!o) return luaL_error(L, "Attempt to call non-existend method"); if (!object_is_method(o)) { lua_stackdump(L); return luaL_error(L, "Attempt to call an event"); } /* Now we're sane! */ buf = lua_to_buffer(L, lnode->node, 5, o); if (!buf) return luaL_error(L, "Serializer failed!"); /* Let's create a table to store our callback and arg */ lua_newtable(L); /* Push the callback function there */ lua_pushnumber(L, 1); lua_pushvalue(L, 3); lua_settable(L, -3); /* And the user argument */ lua_pushnumber(L, 2); lua_pushvalue(L, 4); lua_settable(L, -3); /* And fetch the reference to out table that we'll use in callback */ callback_ref = luaL_ref(L, LUA_REGISTRYINDEX); slog(4, SLOG_DEBUG, "Callback tbl reference: %d", callback_ref); ret = aura_core_start_call(lnode->node, o, calldone_cb, (void *)(long)callback_ref, buf); if (ret != 0) { aura_buffer_release(buf); return luaL_error(L, "Async call for %s failed: %s code (%d)", o->name, strerror(-ret), ret); } return 0; }
bool lupb_checkbool(lua_State *L, int narg) { if (!lua_isboolean(L, narg)) { luaL_error(L, "must be true or false"); } return lua_toboolean(L, narg); }
static int capture_to_close (MatchState *ms) { int level = ms->level; for (level--; level>=0; level--) if (ms->capture[level].len == CAP_UNFINISHED) return level; return luaL_error(ms->L, "invalid pattern capture"); }
static FILE *tofile (lua_State *L, int findex) { FILE **f = topfile(L, findex); if (*f == NULL) luaL_error(L, "attempt to use a closed file"); return *f; }
static int gfind_nodef (lua_State *L) { return luaL_error(L, LUA_QL("string.gfind") " was renamed to " LUA_QL("string.gmatch")); }
static int player_set(lua_State *L) { player_t *plr = *((player_t **)luaL_checkudata(L, 1, META_PLAYER)); const char *field = luaL_checkstring(L, 2); if (!plr) return LUA_ErrInvalid(L, "player_t"); if (hud_running) return luaL_error(L, "Do not alter player_t in HUD rendering code!"); if (fastcmp(field,"mo")) { mobj_t *newmo = *((mobj_t **)luaL_checkudata(L, 3, META_MOBJ)); plr->mo->player = NULL; // remove player pointer from old mobj (newmo->player = plr)->mo = newmo; // set player pointer for new mobj, and set new mobj as the player's mobj } else if (fastcmp(field,"cmd")) return NOSET; else if (fastcmp(field,"playerstate")) plr->playerstate = luaL_checkinteger(L, 3); else if (fastcmp(field,"viewz")) plr->viewz = luaL_checkfixed(L, 3); else if (fastcmp(field,"viewheight")) plr->viewheight = luaL_checkfixed(L, 3); else if (fastcmp(field,"deltaviewheight")) plr->deltaviewheight = luaL_checkfixed(L, 3); else if (fastcmp(field,"bob")) plr->bob = luaL_checkfixed(L, 3); else if (fastcmp(field,"aiming")) { plr->aiming = luaL_checkangle(L, 3); if (plr == &players[consoleplayer]) localaiming = plr->aiming; else if (plr == &players[secondarydisplayplayer]) localaiming2 = plr->aiming; } else if (fastcmp(field,"health")) plr->health = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"pity")) plr->pity = (SINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"currentweapon")) plr->currentweapon = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"ringweapons")) plr->ringweapons = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"powers")) return NOSET; else if (fastcmp(field,"pflags")) plr->pflags = luaL_checkinteger(L, 3); else if (fastcmp(field,"panim")) plr->panim = luaL_checkinteger(L, 3); else if (fastcmp(field,"flashcount")) plr->flashcount = (UINT16)luaL_checkinteger(L, 3); else if (fastcmp(field,"flashpal")) plr->flashpal = (UINT16)luaL_checkinteger(L, 3); else if (fastcmp(field,"skincolor")) { UINT8 newcolor = (UINT8)luaL_checkinteger(L,3); if (newcolor >= MAXSKINCOLORS) return luaL_error(L, "player.skincolor %d out of range (0 - %d).", newcolor, MAXSKINCOLORS-1); plr->skincolor = newcolor; } else if (fastcmp(field,"score")) plr->score = (UINT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"dashspeed")) plr->dashspeed = luaL_checkfixed(L, 3); else if (fastcmp(field,"dashtime")) plr->dashtime = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"normalspeed")) plr->normalspeed = luaL_checkfixed(L, 3); else if (fastcmp(field,"runspeed")) plr->runspeed = luaL_checkfixed(L, 3); else if (fastcmp(field,"thrustfactor")) plr->thrustfactor = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"accelstart")) plr->accelstart = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"acceleration")) plr->acceleration = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"charability")) plr->charability = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"charability2")) plr->charability2 = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"charflags")) plr->charflags = (UINT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"thokitem")) plr->thokitem = luaL_checkinteger(L, 3); else if (fastcmp(field,"spinitem")) plr->spinitem = luaL_checkinteger(L, 3); else if (fastcmp(field,"revitem")) plr->revitem = luaL_checkinteger(L, 3); else if (fastcmp(field,"actionspd")) plr->actionspd = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"mindash")) plr->mindash = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"maxdash")) plr->maxdash = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"jumpfactor")) plr->jumpfactor = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"lives")) plr->lives = (SINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"continues")) plr->continues = (SINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"xtralife")) plr->xtralife = (SINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"gotcontinue")) plr->gotcontinue = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"speed")) plr->speed = luaL_checkfixed(L, 3); else if (fastcmp(field,"jumping")) plr->jumping = luaL_checkboolean(L, 3); else if (fastcmp(field,"secondjump")) plr->secondjump = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"fly1")) plr->fly1 = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"scoreadd")) plr->scoreadd = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"glidetime")) plr->glidetime = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"climbing")) plr->climbing = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"deadtimer")) plr->deadtimer = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"exiting")) plr->exiting = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"homing")) plr->homing = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"skidtime")) plr->skidtime = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"cmomx")) plr->cmomx = luaL_checkfixed(L, 3); else if (fastcmp(field,"cmomy")) plr->cmomy = luaL_checkfixed(L, 3); else if (fastcmp(field,"rmomx")) plr->rmomx = luaL_checkfixed(L, 3); else if (fastcmp(field,"rmomy")) plr->rmomy = luaL_checkfixed(L, 3); else if (fastcmp(field,"numboxes")) plr->numboxes = (INT16)luaL_checkinteger(L, 3); else if (fastcmp(field,"totalring")) plr->totalring = (INT16)luaL_checkinteger(L, 3); else if (fastcmp(field,"realtime")) plr->realtime = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"laps")) plr->laps = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"ctfteam")) plr->ctfteam = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"gotflag")) plr->gotflag = (UINT16)luaL_checkinteger(L, 3); else if (fastcmp(field,"weapondelay")) plr->weapondelay = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"tossdelay")) plr->tossdelay = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"starpostx")) plr->starpostx = (INT16)luaL_checkinteger(L, 3); else if (fastcmp(field,"starposty")) plr->starposty = (INT16)luaL_checkinteger(L, 3); else if (fastcmp(field,"starpostz")) plr->starpostz = (INT16)luaL_checkinteger(L, 3); else if (fastcmp(field,"starpostnum")) plr->starpostnum = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"starposttime")) plr->starposttime = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"starpostangle")) plr->starpostangle = luaL_checkangle(L, 3); else if (fastcmp(field,"angle_pos")) plr->angle_pos = luaL_checkangle(L, 3); else if (fastcmp(field,"old_angle_pos")) plr->old_angle_pos = luaL_checkangle(L, 3); else if (fastcmp(field,"axis1")) P_SetTarget(&plr->axis1, *((mobj_t **)luaL_checkudata(L, 3, META_MOBJ))); else if (fastcmp(field,"axis2")) P_SetTarget(&plr->axis2, *((mobj_t **)luaL_checkudata(L, 3, META_MOBJ))); else if (fastcmp(field,"bumpertime")) plr->bumpertime = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"flyangle")) plr->flyangle = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"drilltimer")) plr->drilltimer = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"linkcount")) plr->linkcount = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"linktimer")) plr->linktimer = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"anotherflyangle")) plr->anotherflyangle = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"nightstime")) plr->nightstime = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"drillmeter")) plr->drillmeter = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"drilldelay")) plr->drilldelay = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"bonustime")) plr->bonustime = luaL_checkboolean(L, 3); else if (fastcmp(field,"capsule")) { mobj_t *mo = NULL; if (!lua_isnil(L, 3)) mo = *((mobj_t **)luaL_checkudata(L, 3, META_MOBJ)); P_SetTarget(&plr->capsule, mo); } else if (fastcmp(field,"mare")) plr->mare = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"marebegunat")) plr->marebegunat = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"startedtime")) plr->startedtime = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"finishedtime")) plr->finishedtime = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"finishedrings")) plr->finishedrings = (INT16)luaL_checkinteger(L, 3); else if (fastcmp(field,"marescore")) plr->marescore = (UINT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"lastmarescore")) plr->lastmarescore = (UINT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"lastmare")) plr->lastmare = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"maxlink")) plr->maxlink = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"texttimer")) plr->texttimer = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"textvar")) plr->textvar = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"lastsidehit")) plr->lastsidehit = (INT16)luaL_checkinteger(L, 3); else if (fastcmp(field,"lastlinehit")) plr->lastlinehit = (INT16)luaL_checkinteger(L, 3); else if (fastcmp(field,"losstime")) plr->losstime = (tic_t)luaL_checkinteger(L, 3); else if (fastcmp(field,"timeshit")) plr->timeshit = (UINT8)luaL_checkinteger(L, 3); else if (fastcmp(field,"onconveyor")) plr->onconveyor = (INT32)luaL_checkinteger(L, 3); else if (fastcmp(field,"awayviewmobj")) { mobj_t *mo = NULL; if (!lua_isnil(L, 3)) mo = *((mobj_t **)luaL_checkudata(L, 3, META_MOBJ)); P_SetTarget(&plr->awayviewmobj, mo); } else if (fastcmp(field,"awayviewtics")) { plr->awayviewtics = (INT32)luaL_checkinteger(L, 3); if (plr->awayviewtics && !plr->awayviewmobj) // awayviewtics must ALWAYS have an awayviewmobj set!! P_SetTarget(&plr->awayviewmobj, plr->mo); // but since the script might set awayviewmobj immediately AFTER setting awayviewtics, use player mobj as filler for now. } else if (fastcmp(field,"awayviewaiming")) plr->awayviewaiming = luaL_checkangle(L, 3); else if (fastcmp(field,"spectator")) plr->spectator = lua_toboolean(L, 3); else if (fastcmp(field,"bot")) return NOSET; else if (fastcmp(field,"jointime")) plr->jointime = (tic_t)luaL_checkinteger(L, 3); #ifdef HWRENDER else if (fastcmp(field,"fovadd")) plr->fovadd = luaL_checkfixed(L, 3); #endif else { lua_getfield(L, LUA_REGISTRYINDEX, LREG_EXTVARS); I_Assert(lua_istable(L, -1)); lua_pushlightuserdata(L, plr); lua_rawget(L, -2); if (lua_isnil(L, -1)) { // This index doesn't have a table for extra values yet, let's make one. lua_pop(L, 1); CONS_Debug(DBG_LUA, M_GetText("'%s' has no field named '%s'; adding it as Lua data.\n"), "player_t", field); lua_newtable(L); lua_pushlightuserdata(L, plr); lua_pushvalue(L, -2); // ext value table lua_rawset(L, -4); // LREG_EXTVARS table } lua_pushvalue(L, 3); // value to store lua_setfield(L, -2, field); lua_pop(L, 2); } return 0; }
int icu_bidi_runs(lua_State *L) { size_t input_l; const char* input = luaL_checklstring(L, 1, &input_l); const char* direction = luaL_checkstring(L, 2); UChar *input_as_uchar; int32_t l; utf8_to_uchar(input, input_l, input_as_uchar, l); UBiDiLevel paraLevel = 0; if (strncasecmp(direction, "RTL", 3) == 0) { paraLevel = 1; } /* Now let's bidi! */ UBiDi* bidi = ubidi_open(); UErrorCode err = U_ZERO_ERROR; ubidi_setPara(bidi, input_as_uchar, l, paraLevel, NULL, &err); if (!U_SUCCESS(err)) { free(input_as_uchar); ubidi_close(bidi); return luaL_error(L, "Error in bidi %s", u_errorName(err)); } int count = ubidi_countRuns(bidi,&err); int start, length; lua_checkstack(L,count); for (int i=0; i < count; i++) { UBiDiDirection dir = ubidi_getVisualRun(bidi, i, &start, &length); lua_newtable(L); // Convert back to UTF8... int32_t l3 = 0; char* possibleOutbuf = malloc(4*length); if(!possibleOutbuf) { return luaL_error(L, "Couldn't malloc"); } u_strToUTF8(possibleOutbuf, 4 * length, &l3, input_as_uchar+start, length, &err); if (!U_SUCCESS(err)) { free(possibleOutbuf); return luaL_error(L, "Bidi run too big? %s", u_errorName(err)); } lua_pushstring(L, "run"); lua_pushstring(L, possibleOutbuf); free(possibleOutbuf); lua_settable(L, -3); lua_pushstring(L, "start"); int32_t new_start = start; // Length/start is given in terms of UTF16 codepoints. // But we want a count of Unicode characters. This means // surrogate pairs need to be counted as 1. for (int j=0; j< start; j++) { if (U_IS_TRAIL(*(input_as_uchar+j))) new_start--; } lua_pushinteger(L, new_start); lua_settable(L, -3); lua_pushstring(L, "length"); for (int j=start; j< start+length; j++) { if (U_IS_TRAIL(*(input_as_uchar+j))) length--; } lua_pushinteger(L, length); lua_settable(L, -3); lua_pushstring(L, "dir"); lua_pushstring(L, dir == UBIDI_RTL ? "RTL" : "LTR"); lua_settable(L, -3); lua_pushstring(L, "level"); lua_pushinteger(L, ubidi_getLevelAt(bidi, start)); lua_settable(L, -3); } free(input_as_uchar); ubidi_close(bidi); return count; }
static int ngx_http_lua_ngx_get(lua_State *L) { ngx_http_request_t *r; u_char *p; size_t len; ngx_http_lua_ctx_t *ctx; lua_pushlightuserdata(L, &ngx_http_lua_request_key); lua_rawget(L, LUA_GLOBALSINDEX); r = lua_touserdata(L, -1); lua_pop(L, 1); if (r == NULL) { return luaL_error(L, "no request object found"); } p = (u_char *) luaL_checklstring(L, -1, &len); dd("ngx get %s", p); if (len == sizeof("status") - 1 && ngx_strncmp(p, "status", sizeof("status") - 1) == 0) { ngx_http_lua_check_fake_request(L, r); lua_pushnumber(L, (lua_Number) r->headers_out.status); return 1; } if (len == sizeof("ctx") - 1 && ngx_strncmp(p, "ctx", sizeof("ctx") - 1) == 0) { return ngx_http_lua_ngx_get_ctx(L); } if (len == sizeof("is_subrequest") - 1 && ngx_strncmp(p, "is_subrequest", sizeof("is_subrequest") - 1) == 0) { lua_pushboolean(L, r != r->main); return 1; } if (len == sizeof("headers_sent") - 1 && ngx_strncmp(p, "headers_sent", sizeof("headers_sent") - 1) == 0) { ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ctx == NULL) { return luaL_error(L, "no ctx"); } ngx_http_lua_check_fake_request2(L, r, ctx); dd("headers sent: %d", ctx->headers_sent); lua_pushboolean(L, ctx->headers_sent ? 1 : 0); return 1; } dd("key %s not matched", p); lua_pushnil(L); return 1; }
int icu_breakpoints(lua_State *L) { const char* input = luaL_checkstring(L, 1); int input_l = strlen(input); const char* locale = luaL_checkstring(L, 2); UChar *buffer; int32_t l, breakcount = 0; UErrorCode err = U_ZERO_ERROR; u_strFromUTF8(NULL, 0, &l, input, input_l, &err); /* Above call returns an error every time. */ err = U_ZERO_ERROR; buffer = malloc(l * sizeof(UChar)); u_strFromUTF8(buffer, l, &l, input, input_l, &err); UBreakIterator* wordbreaks, *linebreaks; int32_t i, previous; wordbreaks = ubrk_open(UBRK_WORD, locale, buffer, l, &err); if(U_FAILURE(err)) { luaL_error(L, "Word break parser failure: %s", u_errorName(err)); } linebreaks = ubrk_open(UBRK_LINE, locale, buffer, l, &err); if(U_FAILURE(err)) { luaL_error(L, "Line break parser failure: %s", u_errorName(err)); } previous = 0; i = 0; while (i <= l) { int32_t out_l; int32_t type; if (!ubrk_isBoundary(linebreaks, i) && !ubrk_isBoundary(wordbreaks,i)) { i++; continue; } lua_checkstack(L, 3); /* At some kind of boundary */ lua_newtable(L); lua_pushstring(L, "type"); lua_pushstring(L, ubrk_isBoundary(linebreaks,i) ? "line" : "word"); lua_settable(L, -3); int32_t utf8_index = 0; err = U_ZERO_ERROR; u_strToUTF8(NULL, 0, &utf8_index, buffer, i, &err); assert(U_SUCCESS(err) || err == U_BUFFER_OVERFLOW_ERROR); lua_pushstring(L, "index"); lua_pushinteger(L, utf8_index); lua_settable(L, -3); if (ubrk_isBoundary(linebreaks, i)) { lua_pushstring(L, "subtype"); type = ubrk_getRuleStatus(linebreaks); if (type >= UBRK_LINE_SOFT && type < UBRK_LINE_SOFT_LIMIT) { lua_pushstring(L, "soft"); } else { lua_pushstring(L, "hard"); } lua_settable(L, -3); } lua_pushstring(L, "token"); lua_pushlstring(L, input+previous, utf8_index-previous); lua_settable(L, -3); previous = utf8_index; breakcount++; i++; } ubrk_close(wordbreaks); ubrk_close(linebreaks); return breakcount; }
static int uart_read( lua_State* L ) { int id, res, mode, issign; unsigned timer_id = 0; s32 timeout = PLATFORM_UART_INFINITE_TIMEOUT, maxsize = 0, count = 0; const char *fmt; luaL_Buffer b; char cres; id = luaL_checkinteger( L, 1 ); MOD_CHECK_ID( uart, id ); // Check format if( lua_isnumber( L, 2 ) ) { if( ( maxsize = ( s32 )lua_tointeger( L, 2 ) ) < 0 ) return luaL_error( L, "invalid max size" ); mode = UART_READ_MODE_MAXSIZE; } else { fmt = luaL_checkstring( L, 2 ); if( !strcmp( fmt, "*l" ) ) mode = UART_READ_MODE_LINE; else if( !strcmp( fmt, "*n" ) ) mode = UART_READ_MODE_NUMBER; else if( !strcmp( fmt, "*s" ) ) mode = UART_READ_MODE_SPACE; else return luaL_error( L, "invalid format" ); } // Check timeout and timer id if( lua_gettop( L ) >= 3 ) { timeout = luaL_checkinteger( L, 3 ); if( ( timeout < 0 ) && ( timeout != PLATFORM_UART_INFINITE_TIMEOUT ) ) return luaL_error( L, "invalid timeout value" ); if( ( timeout != PLATFORM_UART_INFINITE_TIMEOUT ) && ( timeout != 0 ) ) timer_id = luaL_checkinteger( L, 4 ); } // Read data luaL_buffinit( L, &b ); while( 1 ) { if( ( res = platform_uart_recv( id, timer_id, timeout ) ) == -1 ) break; cres = ( char )res; count ++; issign = ( count == 1 ) && ( ( res == '-' ) || ( res == '+' ) ); if( ( cres == '\n' ) && ( mode == UART_READ_MODE_LINE ) ) break; if( !isdigit( cres ) && !issign && ( mode == UART_READ_MODE_NUMBER ) ) break; if( isspace( cres ) && ( mode == UART_READ_MODE_SPACE ) ) break; luaL_putchar( &b, cres ); if( ( count == maxsize ) && ( mode == UART_READ_MODE_MAXSIZE ) ) break; } luaL_pushresult( &b ); // Return an integer if needed if( mode == UART_READ_MODE_NUMBER ) { res = lua_tointeger( L, -1 ); lua_pop( L, 1 ); lua_pushinteger( L, res ); } return 1; }
static int statement_fetch_impl(lua_State *L, statement_t *statement, int named_columns) { int column_count; MYSQL_BIND *bind = NULL; const char *error_message = NULL; if (!statement->stmt) { luaL_error(L, DBI_ERR_FETCH_INVALID); return 0; } if (!statement->metadata) { luaL_error(L, DBI_ERR_FETCH_NO_EXECUTE); return 0; } column_count = mysql_num_fields(statement->metadata); if (column_count > 0) { int i; MYSQL_FIELD *fields; bind = malloc(sizeof(MYSQL_BIND) * column_count); memset(bind, 0, sizeof(MYSQL_BIND) * column_count); fields = mysql_fetch_fields(statement->metadata); for (i = 0; i < column_count; i++) { unsigned int length = mysql_buffer_size(&fields[i]); char *buffer = (char *) malloc(length); memset(buffer, 0, length); bind[i].buffer_type = fields[i].type; bind[i].buffer = buffer; bind[i].buffer_length = length; } if (mysql_stmt_bind_result(statement->stmt, bind)) { error_message = DBI_ERR_BINDING_RESULTS; goto cleanup; } if (!mysql_stmt_fetch(statement->stmt)) { int d = 1; lua_newtable(L); for (i = 0; i < column_count; i++) { lua_push_type_t lua_push = mysql_to_lua_push(fields[i].type); const char *name = fields[i].name; if (lua_push == LUA_PUSH_NIL) { if (named_columns) { LUA_PUSH_ATTRIB_NIL(name); } else { LUA_PUSH_ARRAY_NIL(d); } } else if (lua_push == LUA_PUSH_INTEGER) { if (fields[i].type == MYSQL_TYPE_YEAR || fields[i].type == MYSQL_TYPE_SHORT) { if (named_columns) { LUA_PUSH_ATTRIB_INT(name, *(short *)(bind[i].buffer)); } else { LUA_PUSH_ARRAY_INT(d, *(short *)(bind[i].buffer)); } } else if (fields[i].type == MYSQL_TYPE_TINY) { if (named_columns) { LUA_PUSH_ATTRIB_INT(name, (int)*(char *)(bind[i].buffer)); } else { LUA_PUSH_ARRAY_INT(d, (int)*(char *)(bind[i].buffer)); } } else { if (named_columns) { LUA_PUSH_ATTRIB_INT(name, *(int *)(bind[i].buffer)); } else { LUA_PUSH_ARRAY_INT(d, *(int *)(bind[i].buffer)); } } } else if (lua_push == LUA_PUSH_NUMBER) { if (named_columns) { LUA_PUSH_ATTRIB_FLOAT(name, *(double *)(bind[i].buffer)); } else { LUA_PUSH_ARRAY_FLOAT(d, *(double *)(bind[i].buffer)); } } else if (lua_push == LUA_PUSH_STRING) { if (fields[i].type == MYSQL_TYPE_TIMESTAMP || fields[i].type == MYSQL_TYPE_DATETIME) { char str[20]; struct st_mysql_time *t = bind[i].buffer; snprintf(str, 20, "%d-%02d-%02d %02d:%02d:%02d", t->year, t->month, t->day, t->hour, t->minute, t->second); if (named_columns) { LUA_PUSH_ATTRIB_STRING(name, str); } else { LUA_PUSH_ARRAY_STRING(d, str); } } else if (fields[i].type == MYSQL_TYPE_TIME) { char str[9]; struct st_mysql_time *t = bind[i].buffer; snprintf(str, 9, "%02d:%02d:%02d", t->hour, t->minute, t->second); if (named_columns) { LUA_PUSH_ATTRIB_STRING(name, str); } else { LUA_PUSH_ARRAY_STRING(d, str); } } else if (fields[i].type == MYSQL_TYPE_DATE) { char str[20]; struct st_mysql_time *t = bind[i].buffer; snprintf(str, 11, "%d-%02d-%02d", t->year, t->month, t->day); if (named_columns) { LUA_PUSH_ATTRIB_STRING(name, str); } else { LUA_PUSH_ARRAY_STRING(d, str); } } else { size_t length = bind[i].buffer_length; // // hack for strings. have no idea what 8 means but it is different from value for binary blobs, which is good enough // if (fields[i].charsetnr == 8) { length = min(bind[i].buffer_length, strlen(bind[i].buffer)); } if (named_columns) { LUA_PUSH_ATTRIB_LSTRING(name, bind[i].buffer, length); } else { LUA_PUSH_ARRAY_LSTRING(d, bind[i].buffer, length); } } } else if (lua_push == LUA_PUSH_BOOLEAN) { if (named_columns) { LUA_PUSH_ATTRIB_BOOL(name, *(int *)(bind[i].buffer)); } else { LUA_PUSH_ARRAY_BOOL(d, *(int *)(bind[i].buffer)); } } else { luaL_error(L, DBI_ERR_UNKNOWN_PUSH); } } } else { lua_pushnil(L); } } cleanup: if (bind) { int i; for (i = 0; i < column_count; i++) { free(bind[i].buffer); } free(bind); } if (error_message) { luaL_error(L, error_message, mysql_stmt_error(statement->stmt)); return 0; } return 1; }
static void push_invalid (lua_State *L, STAT_STRUCT *info) { luaL_error(L, "invalid attribute name"); #ifndef _WIN32 info->st_blksize = 0; /* never reached */ #endif }
int libmcache::lua_mcache_open(lua_State* L) { size_t l=0; const char* p=luaL_checklstring(L,1,&l); int fd=-1; if(*p=='/') { if(l>=UNIX_PATH_MAX) return luaL_error(L,err_socket_path_too_long); sockaddr_un sun; sun.sun_family=AF_UNIX; strcpy(sun.sun_path,p); fd=socket(sun.sun_family,SOCK_STREAM,0); if(fd==-1) return luaL_error(L,err_errno,strerror(errno)); if(connect(fd,(sockaddr*)&sun,sizeof(sun))) { close(fd); return luaL_error(L,err_errno,strerror(errno)); } }else { const char* p2=strchr(p,':'); if(!p2) return luaL_error(L,err_invalid_address_format); char tmp[128]; size_t l=p2-p; if(l>sizeof(tmp)-1) return luaL_error(L,err_invalid_address_length); memcpy(tmp,p,l); tmp[l]=0; sockaddr_in sin; sin.sin_family=AF_INET; sin.sin_port=htons(atoi(p2+1)); sin.sin_addr.s_addr=inet_addr(tmp); if(sin.sin_addr.s_addr==INADDR_NONE) { hostent* he=gethostbyname(tmp); if(!he) return luaL_error(L,err_host_is_not_found,tmp); memcpy((char*)&sin.sin_addr.s_addr,he->h_addr,sizeof(sin.sin_addr.s_addr)); } fd=socket(sin.sin_family,SOCK_STREAM,0); if(fd==-1) return luaL_error(L,err_errno,strerror(errno)); if(connect(fd,(sockaddr*)&sin,sizeof(sin))) { close(fd); return luaL_error(L,err_errno,strerror(errno)); } } int on=1; setsockopt(fd,IPPROTO_TCP,TCP_NODELAY,&on,sizeof(on)); FILE* fp=fdopen(fd,"r+"); if(!fp) { close(fd); return luaL_error(L,err_errno,strerror(errno)); } LMCACHE* mcache=(LMCACHE*)lua_newuserdata(L,sizeof(LMCACHE)); luaL_getmetatable(L,LUA_MCACHE); lua_setmetatable(L,-2); mcache->fp=fp; return 1; }
static int queryuserdata_mtcall(lua_State *l) { lua_settop(l, 1); //[u] assert(lua_type(l, 1) == LUA_TUSERDATA); struct queryuserdata *ud = (struct queryuserdata *)lua_touserdata(l, 1); assert(ud != NULL); if(ud->stmt == NULL) { lua_pushnil(l); //[u_] return 1; } int rc = sqlite3_step(ud->stmt); if(rc == SQLITE_DONE) { sqlite3_finalize(ud->stmt); ud->stmt = NULL; lua_pushnil(l); //[u_] return 1; } if(rc != SQLITE_ROW) { lua_pushfstring(l, "Failed to execute statement: %s", sqlite3_errmsg(sqlite3_db_handle(ud->stmt))); sqlite3_finalize(ud->stmt); ud->stmt = NULL; return lua_error(l); } assert(rc == SQLITE_ROW); lua_newtable(l); //[ut] int col = sqlite3_column_count(ud->stmt) - 1; while(col >= 0) { switch(sqlite3_column_type(ud->stmt, col)) { case SQLITE_NULL: lua_pushnil(l); break; case SQLITE_INTEGER: case SQLITE_FLOAT: lua_pushnumber(l, sqlite3_column_double(ud->stmt, col)); break; case SQLITE_TEXT: lua_pushlstring(l, (const char *)sqlite3_column_text(ud->stmt, col), sqlite3_column_bytes(ud->stmt, col)); break; case SQLITE_BLOB: lua_pushlstring(l, (const char *)sqlite3_column_blob(ud->stmt, col), sqlite3_column_bytes(ud->stmt, col)); break; default: assert(0); return luaL_error(l, "Logic Error: unknown col type"); } //[ut?] lua_pushvalue(l, -1); //[ut??] if(ud->intkey) { lua_rawseti(l, -3, col+1); //[ut?] } else { lua_pop(l, 1); //[ut?] } if(ud->assockey) { lua_setfield(l, -2, sqlite3_column_name(ud->stmt, col)); //[ut] } else { lua_pop(l, 1); //[ut] } --col; } return 1; }