int LuaUtils_Introduce(lua_State *L) { int n = LuaUtils_CheckParameter2(L, 1, 2, LuaUtils_IntroduceUsage); if (!lua_istable(L, 1)) return LuaUtils_Error(L, "Not a table"); if (n >= 2) { bool found = false; lua_pushstring(L, "__intrinsic"); lua_gettable(L, -3); if (lua_islightuserdata(L, -1)) { const RegisterItem *items = lua_touserdata(L, -1); const char *library = items[0].name; const char *function = lua_tostring(L, 2); const char *usage = 0; for (const RegisterItem *item = items + 1; item->type; item++) { if (strcmp(function, "introduce") == 0) usage = LuaUtils_IntroduceUsage; if (strcmp(function, item->name) == 0) usage = item->usage; if (usage) break; } if (usage) { luaL_Buffer buffer; luaL_buffinit(L, &buffer); ExpandUsageToBuffer(&buffer, usage, library, function); luaL_pushresult(&buffer); } else { lua_pushstring(L, function); lua_gettable(L, -4); if (lua_isfunction(L, -1) && !lua_iscfunction(L, -1)) { Proto *proto = ((LClosure*) lua_topointer(L, -1))->p; luaL_Buffer buffer; luaL_buffinit(L, &buffer); luaL_addstring(&buffer, "[\""); luaL_addstring(&buffer, library); luaL_addchar(&buffer, '.'); luaL_addstring(&buffer, function); luaL_addchar(&buffer, '('); for (uint16_t i = 0; i < proto->numparams; i++) { if (i) luaL_addchar(&buffer, ','); luaL_addstring(&buffer, getstr(proto->locvars[i].varname)); } if (proto->is_vararg) { if (proto->numparams) luaL_addchar(&buffer, ','); luaL_addstring(&buffer, "..."); } luaL_addstring(&buffer, ")\"]"); luaL_pushresult(&buffer); } else lua_pushstring(L, "<unknown>"); } } } else { luaL_Buffer buffer; luaL_buffinit(L, &buffer); luaL_addchar(&buffer, '['); uint16_t i = 0; { lua_pushnil(L); while (lua_next(L, -2)) { switch (lua_type(L, -1)) { case LUA_TBOOLEAN : // {"name":boolean}, if (i++) luaL_addchar(&buffer, ','); luaL_addstring(&buffer, "{\""); luaL_addstring(&buffer, lua_tostring(L, -2)); luaL_addstring(&buffer, "\":"); luaL_addstring(&buffer, lua_toboolean(L, -1) ? "true" : "false"); luaL_addchar(&buffer, '}'); break; case LUA_TNUMBER : // {"name":number}, if (i++) luaL_addchar(&buffer, ','); luaL_addstring(&buffer, "{\""); luaL_addstring(&buffer, lua_tostring(L, -2)); luaL_addstring(&buffer, "\":"); luaL_addstring(&buffer, lua_tostring(L, -1)); luaL_addchar(&buffer, '}'); break; case LUA_TUSERDATA : case LUA_TLIGHTUSERDATA : // "name", if (i++) luaL_addchar(&buffer, ','); luaL_addchar(&buffer, '"'); luaL_addstring(&buffer, lua_tostring(L, -2)); luaL_addchar(&buffer, '"'); break; } lua_pop(L, 1); } } { lua_pushnil(L); while (lua_next(L, -2)) { if (lua_type(L, -1) == LUA_TFUNCTION) { // "name()", if (i++) luaL_addchar(&buffer, ','); luaL_addchar(&buffer, '"'); luaL_addstring(&buffer, lua_tostring(L, -2)); luaL_addstring(&buffer, "()\""); // TODO Hier "Usage" } lua_pop(L, 1); } } { lua_pushnil(L); while (lua_next(L, -2)) { if (lua_type(L, -1) == LUA_TTABLE) { // "name", if (i++) luaL_addchar(&buffer, ','); luaL_addchar(&buffer, '"'); luaL_addstring(&buffer, lua_tostring(L, -2)); luaL_addstring(&buffer, ".*\""); } lua_pop(L, 1); } } luaL_addchar(&buffer, ']'); luaL_pushresult(&buffer); } return 1; }
void sinsp_chisel::parse_view_column(lua_State *ls, OUT chisel_desc* cd, OUT void* columns) { vector<sinsp_view_column_info>* cols = (vector<sinsp_view_column_info>*)columns; lua_pushnil(ls); string tmpstr; string name; string description; string field; uint32_t colsize = 0xffffffff; uint32_t flags = TEF_NONE; sinsp_field_aggregation aggregation = A_NONE; sinsp_field_aggregation groupby_aggregation = A_NONE; vector<string> tags; while(lua_next(ls, -2) != 0) { string fldname = lua_tostring(ls, -2); if(fldname == "name") { name = lua_tostring(ls, -1); } else if(fldname == "description") { description = lua_tostring(ls, -1); } else if(fldname == "field") { field = lua_tostring(ls, -1); } else if(fldname == "colsize") { if(lua_isnumber(ls, -1)) { colsize = (uint32_t)lua_tonumber(ls, -1); } else { throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a number"); } } else if(fldname == "is_key") { if(lua_isboolean(ls, -1)) { bool ik = (lua_toboolean(ls, -1) != 0); if(ik) { flags |= TEF_IS_KEY; } } else { throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a boolean value"); } } else if(fldname == "is_groupby_key") { if(lua_isboolean(ls, -1)) { bool ik = (lua_toboolean(ls, -1) != 0); if(ik) { flags |= TEF_IS_GROUPBY_KEY; } } else { throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a boolean value"); } } else if(fldname == "is_sorting") { if(lua_isboolean(ls, -1)) { bool ik = (lua_toboolean(ls, -1) != 0); if(ik) { flags |= TEF_IS_SORT_COLUMN; } } else { throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a boolean value"); } } else if(fldname == "aggregation") { if(lua_isstring(ls, -1)) { string ag = lua_tostring(ls, -1); aggregation = string_to_aggregation(ag); } } else if(fldname == "groupby_aggregation") { if(lua_isstring(ls, -1)) { string ag = lua_tostring(ls, -1); groupby_aggregation = string_to_aggregation(ag); } } else if(fldname == "tags") { if(lua_istable(ls, -1)) { lua_pushnil(ls); while(lua_next(ls, -2) != 0) { if(lua_isstring(ls, -1)) { tmpstr = lua_tostring(ls, -1); tags.push_back(tmpstr); } else { throw sinsp_exception("tags column entries must be strings"); } lua_pop(ls, 1); } } else { throw sinsp_exception(string(lua_tostring(ls, -2)) + " is not a table"); } } lua_pop(ls, 1); } cols->push_back(sinsp_view_column_info(field, name, description, colsize, (uint32_t)flags, aggregation, groupby_aggregation, tags)); }
/* ** Read the options specified in the ini file. ** */ void CMeasureScript::ReadOptions(CConfigParser& parser, const WCHAR* section) { CMeasure::ReadOptions(parser, section); std::wstring file = parser.ReadString(section, L"ScriptFile", L""); if (!file.empty()) { if (m_MeterWindow) { m_MeterWindow->MakePathAbsolute(file); } if (!m_Initialized || wcscmp(file.c_str(), m_ScriptFile.c_str()) != 0) { DeleteLuaScript(); lua_State* L = LuaManager::GetState(); m_ScriptFile = file; m_LuaScript = new LuaScript(m_ScriptFile.c_str()); if (m_LuaScript->IsInitialized()) { m_HasInitializeFunction = m_LuaScript->IsFunction(g_InitializeFunctionName); m_HasUpdateFunction = m_LuaScript->IsFunction(g_UpdateFunctionName); m_HasGetStringFunction = m_LuaScript->IsFunction(g_GetStringFunctionName); // For backwards compatbility if (m_HasGetStringFunction) { LogWithArgs(LOG_WARNING, L"Script: Using deprecated GetStringValue() in [%s]", m_Name.c_str()); } lua_rawgeti(L, LUA_GLOBALSINDEX, m_LuaScript->GetRef()); *(CMeterWindow**)lua_newuserdata(L, sizeof(CMeterWindow*)) = m_MeterWindow; lua_getglobal(L, "CMeterWindow"); lua_setmetatable(L, -2); lua_setfield(L, -2, "SKIN"); *(CMeasure**)lua_newuserdata(L, sizeof(CMeasure*)) = this; lua_getglobal(L, "CMeasure"); lua_setmetatable(L, -2); lua_setfield(L, -2, "SELF"); // For backwards compatibility lua_getfield(L, -1, "PROPERTIES"); if (lua_isnil(L, -1) == 0) { lua_pushnil(L); // Look in the table for values to read from the section while (lua_next(L, -2)) { lua_pop(L, 1); const char* strKey = lua_tostring(L, -1); std::wstring wstrKey = ConvertToWide(strKey); const std::wstring& wstrValue = parser.ReadString(section, wstrKey.c_str(), L""); if (!wstrValue.empty()) { LuaManager::PushWide(L, wstrValue.c_str()); lua_setfield(L, -3, strKey); } } } // Pop PROPERTIES table and our table lua_pop(L, 2); } else { DeleteLuaScript(); } } } else { LogWithArgs(LOG_ERROR, L"Script: File not valid in [%s]", m_Name.c_str()); DeleteLuaScript(); } }
int addon_output_init(struct output *o) { struct addon *addon = o->info->reg_info->mod->priv; lua_State *L = addon_create_state(addon->filename); // Stack : empty if (!L) { pomlog(POMLOG_ERR "Error while creating new lua state for output %s", o->info->reg_info->name); return POM_ERR; } // Get the output from the outputs table lua_getfield(L, LUA_REGISTRYINDEX, ADDON_OUTPUTS_TABLE); // Stack : outputs lua_getfield(L, -1, o->info->reg_info->name); // Stack : outputs, output // Get rid of the outputs table lua_remove(L, -2); // Stack : output lua_pushnil(L); // Stack : output, nil lua_setfield(L, LUA_REGISTRYINDEX, ADDON_OUTPUTS_TABLE); // Stack : output // Add the output to the registry lua_pushvalue(L, -1); // Stack : output, output lua_setfield(L, LUA_REGISTRYINDEX, ADDON_INSTANCE); // Stack : output // Create the private data // TODO make __priv read-only struct addon_instance_priv *p = lua_newuserdata(L, sizeof(struct addon_instance_priv)); // Stack : output, priv if (!p) { pom_oom(sizeof(struct addon_instance_priv)); return POM_ERR; } memset(p, 0, sizeof(struct addon_instance_priv)); o->priv = p; p->instance = o; p->L = L; if (pthread_mutex_init(&p->lock, NULL)) { pomlog(POMLOG_ERR "Error while initializing mutex : %s", pom_strerror(errno)); abort(); return POM_ERR; } // Assign the output_priv metatable luaL_getmetatable(L, ADDON_OUTPUT_PRIV_METATABLE); // Stack : output, priv, metatable lua_setmetatable(L, -2); // Stack : output, priv // Add it to __priv lua_setfield(L, -2, "__priv"); // Stack : output // Fetch the parameters table lua_getfield(L, -1, "__params"); // Stack : output, params // Parse each param from the class lua_pushnil(L); // Stack : output, params, nil while (lua_next(L, -2) != 0) { // Stack : output, params, key, param if (!lua_istable(L, -1)) { pomlog(POMLOG_ERR "Parameters should be described in tables"); goto err; } // Fetch the name lua_pushinteger(L, 1); // Stack : output, params, key, param, 1 lua_gettable(L, -2); // Stack : output, params, key, param, name if (!lua_isstring(L, -1)) { pomlog(POMLOG_ERR "Parameter name is not a string"); goto err; } const char *name = luaL_checkstring(L, -1); lua_pop(L, 1); // Stack : output, params, key, param // Fetch the ptype type lua_pushinteger(L, 2); // Stack : output, params, key, param, 2 lua_gettable(L, -2); // Stack : output, params, key, param, type if (!lua_isstring(L, -1)) { pomlog(POMLOG_ERR "Parameter type is not a string"); goto err; } const char *type = lua_tostring(L, -1); lua_pop(L, 1); // Stack : output, params, key, param // Fetch the default value lua_pushinteger(L, 3); // Stack : output, params, key, param, 3 lua_gettable(L, -2); // Stack : output, params, key, param, defval if (!lua_isstring(L, -1)) { pomlog(POMLOG_ERR "Parameter default value is not a string"); goto err; } const char *defval = lua_tostring(L, -1); lua_pop(L, 1); // Stack : output, params, key, param // Fetch the description lua_pushinteger(L, 4); // Stack : output, params, key, param, 4 lua_gettable(L, -2); // Stack : output, params, key, param, descr if (!lua_isstring(L, -1)) { pomlog(POMLOG_ERR "Parameter description is not a string"); goto err; } const char *descr = lua_tostring(L, -1); lua_pop(L, 1); // Stack : output, params, key, param // Allocate it struct addon_param *param = malloc(sizeof(struct addon_param)); if (!param) { pom_oom(sizeof(struct addon_param)); goto err; } param->name = strdup(name); if (!param->name) { free(param); pom_oom(strlen(name) + 1); goto err; } param->value = ptype_alloc(type); if (!param->value) { free(param->name); free(param); goto err; } struct registry_param *reg_param = registry_new_param((char*)name, (char*)defval, param->value, (char*)descr, 0); if (output_add_param(o, reg_param) != POM_OK) { pomlog(POMLOG_ERR "Error while adding parameter to the output instance"); if (reg_param) registry_cleanup_param(reg_param); free(param->name); ptype_cleanup(param->value); free(param); goto err; } param->next = p->params; p->params = param; // Pop the value (the param table) lua_pop(L, 1); // Stack : output, params, key } // At this point the stack is : output, params lua_pop(L, 2); // Stack : empty pomlog(POMLOG_DEBUG "Output %s created", o->name); return POM_OK; err: lua_close(L); p->L = NULL; return POM_ERR; }
/* Returns 0 on success, non-zero on failure */ static int save_table( lua_State * L, luabins_SaveBuffer * sb, int index, int nesting ) { int result = LUABINS_ESUCCESS; int header_pos = 0; int total_size = 0; if (nesting > LUABINS_MAXTABLENESTING) { return LUABINS_ETOODEEP; } /* TODO: Hauling stack for key and value removal may get too heavy for larger tables. Think out a better way. */ header_pos = lbsSB_length(sb); result = lbs_writeTableHeader(sb, 0, 0); result = lbsSB_grow(sb, LUABINS_LINT + LUABINS_LINT); if (result == LUABINS_ESUCCESS) { lua_checkstack(L, 2); /* Key and value */ lua_pushnil(L); /* key for lua_next() */ } while (result == LUABINS_ESUCCESS && lua_next(L, index) != 0) { int value_pos = lua_gettop(L); /* We need absolute values */ int key_pos = value_pos - 1; /* Save key. */ result = save_value(L, sb, key_pos, nesting); /* Save value. */ if (result == LUABINS_ESUCCESS) { result = save_value(L, sb, value_pos, nesting); } if (result == LUABINS_ESUCCESS) { /* Remove value from stack, leave key for the next iteration. */ lua_pop(L, 1); ++total_size; } } if (result == LUABINS_ESUCCESS) { /* Note that if array has holes, lua_objlen() may report larger than actual array size. So we need to adjust. TODO: Note inelegant downsize from size_t to int. Handle integer overflow here. */ int array_size = luabins_min(total_size, (int)lua_rawlen(L, index)); int hash_size = luabins_max(0, total_size - array_size); result = lbs_writeTableHeaderAt(sb, header_pos, array_size, hash_size); } return result; }
static int autotype_next(lua_State *L) { /* CONVENTION each block has the following stack on entry and exit 1 : the object 2 : the last entry ("next" convention) each block should return according to "next" convention on success each block should leave the key untouched if it doesn't know about it each block should replace the key with "nil" if the key was the last entry it can handle */ // printf("aaaaa %s %d\n",__FUNCTION__,__LINE__); if(luaL_getmetafield(L, 1, "__len")) { lua_pushvalue(L, -3); lua_call(L, 1, 1); int length = lua_tonumber(L, -1); lua_pop(L, 1); int key = 0; if(lua_isnil(L, -1) && length > 0) { key = 1; } else if(lua_isnumber(L, -1) && lua_tonumber(L, -1) < length) { key = lua_tonumber(L, -1) + 1; } else if(lua_isnumber(L, -1) && lua_tonumber(L, -1) == length) { // numbers are done, move-on to something else lua_pop(L, 1); lua_pushnil(L); } if(key) { lua_pop(L, 1); lua_pushnumber(L, key); lua_pushnumber(L, key); lua_gettable(L, -3); return 2; } } // stack at this point : {object,key} int key_in_get = false; luaL_getmetafield(L, 1, "__get"); if(lua_isnil(L, -2)) { key_in_get = true; } else { lua_pushvalue(L, -2); lua_gettable(L, -2); if(lua_isnil(L, -1)) { key_in_get = false; lua_pop(L, 2); } else { key_in_get = true; lua_pop(L, 1); } } if(key_in_get) { lua_pushvalue(L, -2); int nil_found = false; while(!nil_found) { if(lua_next(L, -2)) { // we have a next lua_pop(L, 1); lua_pushvalue(L, -4); lua_pushvalue(L, -2); // hacky way to avoid a subfunction just to do a pcall around getting a value in a table int result = dt_lua_dostring(L, "args ={...}; return args[1][args[2]]", 2, 1); if(result == LUA_OK) { return 2; } else { lua_pop(L, 1); // and loop to find the next possible value } } else { // key was the last for __get lua_pop(L, 2); lua_pushnil(L); nil_found = true; } } } // stack at this point : {object,key} if(lua_isnil(L, -1)) { return 1; } else { return luaL_error(L, "invalid key to 'next' : %s", lua_tostring(L, 2)); } }
bool LuaInterface::next(int index) { assert(hasIndex(index)); return lua_next(L, index); }
static size_t ngx_http_lua_calc_strlen_in_table(lua_State *L, int arg_i) { double key; int max; int i; int type; size_t size; size_t len; const char *msg; max = 0; lua_pushnil(L); /* stack: table key */ while (lua_next(L, -2) != 0) { /* stack: table key value */ if (lua_type(L, -2) == LUA_TNUMBER && (key = lua_tonumber(L, -2))) { if (floor(key) == key && key >= 1) { if (key > max) { max = key; } lua_pop(L, 1); /* stack: table key */ continue; } } /* not an array (non positive integer key) */ lua_pop(L, 2); /* stack: table */ msg = lua_pushfstring(L, "on-array table found"); luaL_argerror(L, arg_i, msg); return 0; } size = 0; for (i = 1; i <= max; i++) { lua_rawgeti(L, -1, i); /* stack: table value */ type = lua_type(L, -1); switch (type) { case LUA_TNUMBER: case LUA_TSTRING: lua_tolstring(L, -1, &len); size += len; break; case LUA_TNIL: size += sizeof("nil") - 1; break; case LUA_TBOOLEAN: if (lua_toboolean(L, -1)) { size += sizeof("true") - 1; } else { size += sizeof("false") - 1; } break; case LUA_TTABLE: size += ngx_http_lua_calc_strlen_in_table(L, arg_i); break; default: msg = lua_pushfstring(L, "bad data type %s found", lua_typename(L, type)); luaL_argerror(L, arg_i, msg); return 0; } lua_pop(L, 1); /* stack: table */ } return size; }
static u_char * ngx_http_lua_copy_str_in_table(lua_State *L, u_char *dst) { double key; int max; int i; int type; size_t len; u_char *p; max = 0; lua_pushnil(L); /* stack: table key */ while (lua_next(L, -2) != 0) { /* stack: table key value */ key = lua_tonumber(L, -2); if (key > max) { max = key; } lua_pop(L, 1); /* stack: table key */ } for (i = 1; i <= max; i++) { lua_rawgeti(L, -1, i); /* stack: table value */ type = lua_type(L, -1); switch (type) { case LUA_TNUMBER: case LUA_TSTRING: p = (u_char *) lua_tolstring(L, -1, &len); dst = ngx_copy(dst, p, len); break; case LUA_TNIL: *dst++ = 'n'; *dst++ = 'i'; *dst++ = 'l'; break; case LUA_TBOOLEAN: if (lua_toboolean(L, -1)) { *dst++ = 't'; *dst++ = 'r'; *dst++ = 'u'; *dst++ = 'e'; } else { *dst++ = 'f'; *dst++ = 'a'; *dst++ = 'l'; *dst++ = 's'; *dst++ = 'e'; } break; case LUA_TTABLE: dst = ngx_http_lua_copy_str_in_table(L, dst); break; default: luaL_error(L, "impossible to reach here"); return NULL; } lua_pop(L, 1); /* stack: table */ } return dst; }
Entity *LuaScripting::LoadEntity(const char *_entityFile) { if (RunScript(_entityFile)) { lua_getglobal(m_luaState, "name"); if (lua_isstring(m_luaState, -1)) { Entity *e = new Entity(0, lua_tostring(m_luaState, -1)); Vector position; position.x = position.y = 100; position.z = 0; e->SetProperty("position", TYPE_VECTOR, (void*)&position); lua_pop(m_luaState, 1); lua_getglobal(m_luaState, "properties"); if (lua_istable(m_luaState, -1)) { lua_pushnil(m_luaState); while(lua_next(m_luaState, -2) != 0) { const char *propertyName = NULL; if (!lua_isnumber(m_luaState, -2) && lua_isstring(m_luaState, -2)) { propertyName = lua_tostring(m_luaState, -2); int type = lua_type(m_luaState, -1); if (propertyName != NULL) { switch (type) { case LUA_TSTRING: e->SetProperty(propertyName, TYPE_STRING, (void*)lua_tostring(m_luaState, -1)); break; case LUA_TNUMBER: { float f = lua_tonumber(m_luaState, -1); e->SetProperty(propertyName, TYPE_NUMBER, (void*)&f); break; } case LUA_TBOOLEAN: { bool b = lua_toboolean(m_luaState, -1); e->SetProperty(propertyName, TYPE_BOOLEAN, (void*)&b); break; } case LUA_TUSERDATA: if (lua_isusertype(m_luaState, -1, "Rect")) { e->SetProperty(propertyName, TYPE_RECT, tolua_tousertype(m_luaState, -1, 0)); break; } else if (lua_isusertype(m_luaState, -1, "Vector")) { e->SetProperty(propertyName, TYPE_VECTOR, tolua_tousertype(m_luaState, -1, 0)); break; } else { g_console->WriteLine("WARN: Unknown property type detected, please fix."); } break; default: g_console->WriteLine("WARN: Property values must one of the following types: String, Number, Boolean, Rect, Vector"); break; } } } lua_pop(m_luaState, 1); } } lua_getglobal(m_luaState, "behaviors"); if (lua_istable(m_luaState, -1)) { // -1 is the table // Loop through behaviors table lua_pushnil(m_luaState); // -1 is the first key while(lua_next(m_luaState, -2) != 0) { // -2: behaviors table const char *behaviorName = NULL; if (!lua_isnumber(m_luaState, -1) && lua_isstring(m_luaState, -1)) { behaviorName = lua_tostring(m_luaState, -1); } else if (!lua_isnumber(m_luaState, -2) && lua_isstring(m_luaState, -2)) { behaviorName = lua_tostring(m_luaState, -2); } else { g_console->WriteLine("WARN: Non-string entry found in behaviors table, please fix."); } if (behaviorName != NULL) { behaviorFunc f = get_behavior(behaviorName); if (f == NULL) { g_console->WriteLine("WARN: '%s' is not a registered behavior.", behaviorName); } else { e->AddBehavior(behaviorName, f); } } lua_pop(m_luaState, 1); } } /* Look for input hooks */ /* onKeyUp */ lua_getglobal(m_luaState, "onKeyUp"); if (lua_isfunction(m_luaState, -1)) { g_input->RegisterEventObserver(SDL_KEYUP, e); } /* onKeyDown */ lua_getglobal(m_luaState, "onKeyDown"); if (lua_isfunction(m_luaState, -1)) { g_input->RegisterEventObserver(SDL_KEYDOWN, e); } /* onMouseDown */ lua_getglobal(m_luaState, "onMouseDown"); if (lua_isfunction(m_luaState, -1)) { g_input->RegisterEventObserver(SDL_MOUSEBUTTONDOWN, e); } /* onMouseUp */ lua_getglobal(m_luaState, "onMouseUp"); if (lua_isfunction(m_luaState, -1)) { g_input->RegisterEventObserver(SDL_MOUSEBUTTONUP, e); } /* onMouseOver */ lua_getglobal(m_luaState, "onMouseOver"); if (lua_isfunction(m_luaState, -1)) { g_input->RegisterEventObserver(MOUSE_OVER, e); } /* onMouseLeave */ lua_getglobal(m_luaState, "onMouseLeave"); if (lua_isfunction(m_luaState, -1)) { g_input->RegisterEventObserver(MOUSE_LEAVE, e); } ResetEntityFileGlobals(); return e; } ResetEntityFileGlobals(); g_console->WriteLine("ERROR: Missing field: 'name'"); } g_console->WriteLine("FAIL: Could not parse the entity file."); return NULL; }
/* ** Read the options specified in the ini file. ** */ void MeasureScript::ReadOptions(ConfigParser& parser, const WCHAR* section) { Measure::ReadOptions(parser, section); std::wstring scriptFile = parser.ReadString(section, L"ScriptFile", L""); if (!scriptFile.empty()) { if (m_MeterWindow) { m_MeterWindow->MakePathAbsolute(scriptFile); } if (!m_Initialized || wcscmp(scriptFile.c_str(), m_LuaScript.GetFile().c_str()) != 0) { UninitializeLuaScript(); lua_State* L = LuaManager::GetState(); if (m_LuaScript.Initialize(scriptFile)) { bool hasInitializeFunction = m_LuaScript.IsFunction(g_InitializeFunctionName); m_HasUpdateFunction = m_LuaScript.IsFunction(g_UpdateFunctionName); m_HasGetStringFunction = m_LuaScript.IsFunction(g_GetStringFunctionName); // For backwards compatbility if (m_HasGetStringFunction) { LogWarningF(this, L"Script: Using deprecated GetStringValue()"); } lua_rawgeti(L, LUA_GLOBALSINDEX, m_LuaScript.GetRef()); *(MeterWindow**)lua_newuserdata(L, sizeof(MeterWindow*)) = m_MeterWindow; lua_getglobal(L, "MeterWindow"); lua_setmetatable(L, -2); lua_setfield(L, -2, "SKIN"); *(Measure**)lua_newuserdata(L, sizeof(Measure*)) = this; lua_getglobal(L, "Measure"); lua_setmetatable(L, -2); lua_setfield(L, -2, "SELF"); // For backwards compatibility lua_getfield(L, -1, "PROPERTIES"); if (lua_isnil(L, -1) == 0) { lua_pushnil(L); // Look in the table for values to read from the section while (lua_next(L, -2)) { lua_pop(L, 1); const char* strKey = lua_tostring(L, -1); std::wstring wstrKey = StringUtil::Widen(strKey); const std::wstring& wstrValue = parser.ReadString(section, wstrKey.c_str(), L""); if (!wstrValue.empty()) { std::string strStrVal = StringUtil::Narrow(wstrValue); const char* strValue = strStrVal.c_str(); lua_pushstring(L, strValue); lua_setfield(L, -3, strKey); } } } // Pop PROPERTIES table and our table lua_pop(L, 2); if (m_Initialized) { // If the measure is already initialized and the script has changed, we need to // manually call Initialize(). Initialize(); } // Valid script. return; } } else if (m_LuaScript.IsInitialized()) { // Already initialized. return; } } LogErrorF(this, L"Script: File not valid"); UninitializeLuaScript(); }
bool read_schematic_def(lua_State *L, int index, Schematic *schem, std::vector<std::string> *names) { if (!lua_istable(L, index)) return false; //// Get schematic size lua_getfield(L, index, "size"); v3s16 size = check_v3s16(L, -1); lua_pop(L, 1); schem->size = size; //// Get schematic data lua_getfield(L, index, "data"); luaL_checktype(L, -1, LUA_TTABLE); int numnodes = size.X * size.Y * size.Z; schem->schemdata = new MapNode[numnodes]; int i = 0; size_t names_base = names->size(); std::map<std::string, content_t> name_id_map; lua_pushnil(L); while (lua_next(L, -2)) { if (i >= numnodes) { i++; lua_pop(L, 1); continue; } // same as readnode, except param1 default is MTSCHEM_PROB_CONST lua_getfield(L, -1, "name"); std::string name = luaL_checkstring(L, -1); lua_pop(L, 1); u8 param1; lua_getfield(L, -1, "param1"); param1 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : MTSCHEM_PROB_ALWAYS; lua_pop(L, 1); u8 param2; lua_getfield(L, -1, "param2"); param2 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : 0; lua_pop(L, 1); std::map<std::string, content_t>::iterator it = name_id_map.find(name); content_t name_index; if (it != name_id_map.end()) { name_index = it->second; } else { name_index = names->size() - names_base; name_id_map[name] = name_index; names->push_back(name); } schem->schemdata[i] = MapNode(name_index, param1, param2); i++; lua_pop(L, 1); } if (i != numnodes) { errorstream << "read_schematic_def: incorrect number of " "nodes provided in raw schematic data (got " << i << ", expected " << numnodes << ")." << std::endl; return false; } //// Get Y-slice probability values (if present) schem->slice_probs = new u8[size.Y]; for (i = 0; i != size.Y; i++) schem->slice_probs[i] = MTSCHEM_PROB_ALWAYS; lua_getfield(L, index, "yslice_prob"); if (lua_istable(L, -1)) { lua_pushnil(L); while (lua_next(L, -2)) { if (getintfield(L, -1, "ypos", i) && i >= 0 && i < size.Y) { schem->slice_probs[i] = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); } lua_pop(L, 1); } } return true; }
bool PopVariant(lua_State *pLuaState, Variant &variant, int32_t idx, bool pop) { variant.Reset(); int32_t type = lua_type(pLuaState, idx); switch (type) { case LUA_TNIL: { variant.Reset(); if (pop) lua_remove(pLuaState, idx); break; } case LUA_TBOOLEAN: { variant = (bool)(lua_toboolean(pLuaState, idx) != 0); if (pop) lua_remove(pLuaState, idx); break; } case LUA_TNUMBER: { lua_Number luaNumber = lua_tonumber(pLuaState, idx); if (pop) lua_remove(pLuaState, idx); variant = (double) luaNumber; variant.Compact(); break; } case LUA_TSTRING: { string nullable = lua_tostring(pLuaState, idx); if (pop) lua_remove(pLuaState, idx); if (nullable == VAR_NULL_VALUE) variant = Variant(); else variant = nullable; break; } case LUA_TTABLE: { bool isArray = true; lua_pushnil(pLuaState); while (lua_next(pLuaState, idx) != 0) { Variant value; if (!PopVariant(pLuaState, value, lua_gettop(pLuaState))) return false; Variant key; if (!PopVariant(pLuaState, key, lua_gettop(pLuaState), false)) return false; variant[key] = value; isArray &= (key == _V_NUMERIC); } variant.IsArray(isArray); if (variant.HasKey(VAR_MAP_NAME)) { variant.SetTypeName(variant[VAR_MAP_NAME]); variant.RemoveKey(VAR_MAP_NAME); } else { variant.ConvertToTimestamp(); } if (pop) lua_remove(pLuaState, idx); break; } default: { WARN("Element type not supported: %d (0x%x)", type, type); return false; break; } } return true; }
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; }
static void value_to_stringstream( std::stringstream& output, int i, lua_State* L, std::string indent, const bool verbose_table = true) { const int t = lua_type(L, i); switch (t) { case LUA_TSTRING: output << "STRING; VALUE: " << lua_tostring(L, i); break; case LUA_TBOOLEAN: output << "BOOLEAN; VALUE: " << (lua_toboolean(L, i) ? "true" : "false"); break; case LUA_TNUMBER: output << "NUMBER; VALUE: " << lua_tonumber(L, i); break; case LUA_TNIL: output << "NIL; VALUE: nil"; break; case LUA_TTABLE: { output << "TABLE; VALUE: " << lua_topointer(L, i); if(verbose_table) { indent += "\t"; unsigned keyindex = lua_gettop(L) + 1; lua_pushnil(L); while(lua_next(L, i) != 0) { output << "\n" << indent << "KEY: "; const int keytype = lua_type(L, keyindex); switch(keytype) { case LUA_TSTRING: output << lua_tostring(L, keyindex); break; case LUA_TBOOLEAN: output << (lua_toboolean(L, keyindex) ? "true" : "false"); break; case LUA_TNUMBER: output << lua_tonumber(L, keyindex); break; default: output << lua_topointer(L, keyindex); break; } output << "; TYPE: "; value_to_stringstream(output, keyindex + 1, L, indent); lua_pop(L, 1); } } } break; case LUA_TUSERDATA: output << "USERDATA; VALUE: " << lua_topointer(L, i); break; case LUA_TFUNCTION: output << "FUNCTION; VALUE: " << lua_topointer(L, i); break; case LUA_TTHREAD: output << "THREAD; VALUE: " << lua_topointer(L, i); break; case LUA_TLIGHTUSERDATA: output << "LIGHTUSERDATA; VALUE: " << lua_topointer(L, i); break; default: //There are no other types! assert(false); break; } }
int DetectLuajitMatchBuffer(DetectEngineThreadCtx *det_ctx, Signature *s, SigMatch *sm, uint8_t *buffer, uint32_t buffer_len, uint32_t offset) { SCEnter(); int ret = 0; if (buffer == NULL || buffer_len == 0) SCReturnInt(0); DetectLuajitData *luajit = (DetectLuajitData *)sm->ctx; if (luajit == NULL) SCReturnInt(0); DetectLuajitThreadData *tluajit = (DetectLuajitThreadData *)DetectThreadCtxGetKeywordThreadCtx(det_ctx, luajit->thread_ctx_id); if (tluajit == NULL) SCReturnInt(0); lua_getglobal(tluajit->luastate, "match"); lua_newtable(tluajit->luastate); /* stack at -1 */ lua_pushliteral (tluajit->luastate, "offset"); /* stack at -2 */ lua_pushnumber (tluajit->luastate, (int)(offset + 1)); lua_settable(tluajit->luastate, -3); lua_pushstring (tluajit->luastate, luajit->buffername); /* stack at -2 */ lua_pushlstring (tluajit->luastate, (const char *)buffer, (size_t)buffer_len); lua_settable(tluajit->luastate, -3); int retval = lua_pcall(tluajit->luastate, 1, 1, 0); if (retval != 0) { SCLogInfo("failed to run script: %s", lua_tostring(tluajit->luastate, -1)); } /* process returns from script */ if (lua_gettop(tluajit->luastate) > 0) { /* script returns a number (return 1 or return 0) */ if (lua_type(tluajit->luastate, 1) == LUA_TNUMBER) { double script_ret = lua_tonumber(tluajit->luastate, 1); SCLogDebug("script_ret %f", script_ret); lua_pop(tluajit->luastate, 1); if (script_ret == 1.0) ret = 1; /* script returns a table */ } else if (lua_type(tluajit->luastate, 1) == LUA_TTABLE) { lua_pushnil(tluajit->luastate); const char *k, *v; while (lua_next(tluajit->luastate, -2)) { v = lua_tostring(tluajit->luastate, -1); lua_pop(tluajit->luastate, 1); k = lua_tostring(tluajit->luastate, -1); if (!k || !v) continue; SCLogDebug("k='%s', v='%s'", k, v); if (strcmp(k, "retval") == 0) { if (atoi(v) == 1) ret = 1; } else { /* set flow var? */ } } /* pop the table */ lua_pop(tluajit->luastate, 1); } } else { SCLogDebug("no stack"); } if (luajit->negated) { if (ret == 1) ret = 0; else ret = 1; } SCReturnInt(ret); }
void MissileType::Load(lua_State *l) { this->NumDirections = 1; this->Flip = true; // Ensure we don't divide by zero. this->SplashFactor = 100; // Parse the arguments std::string file; for (lua_pushnil(l); lua_next(l, 2); lua_pop(l, 1)) { const char *value = LuaToString(l, -2); if (!strcmp(value, "File")) { file = LuaToString(l, -1); } else if (!strcmp(value, "Size")) { if (!lua_istable(l, -1) || lua_rawlen(l, -1) != 2) { LuaError(l, "incorrect argument"); } lua_rawgeti(l, -1, 1); this->size.x = LuaToNumber(l, -1); lua_pop(l, 1); lua_rawgeti(l, -1, 2); this->size.y = LuaToNumber(l, -1); lua_pop(l, 1); } else if (!strcmp(value, "Frames")) { this->SpriteFrames = LuaToNumber(l, -1); } else if (!strcmp(value, "Flip")) { this->Flip = LuaToBoolean(l, -1); } else if (!strcmp(value, "NumDirections")) { this->NumDirections = LuaToNumber(l, -1); } else if (!strcmp(value, "Transparency")) { this->Transparency = LuaToNumber(l, -1); } else if (!strcmp(value, "FiredSound")) { this->FiredSound.Name = LuaToString(l, -1); } else if (!strcmp(value, "ImpactSound")) { this->ImpactSound.Name = LuaToString(l, -1); } else if (!strcmp(value, "ChangeVariable")) { const int index = UnitTypeVar.VariableNameLookup[LuaToString(l, -1)];// User variables if (index == -1) { fprintf(stderr, "Bad variable name '%s'\n", LuaToString(l, -1)); Exit(1); return; } this->ChangeVariable = index; } else if (!strcmp(value, "ChangeAmount")) { this->ChangeAmount = LuaToNumber(l, -1); } else if (!strcmp(value, "ChangeMax")) { this->ChangeMax = LuaToBoolean(l, -1); } else if (!strcmp(value, "Class")) { const char *className = LuaToString(l, -1); unsigned int i = 0; for (; MissileClassNames[i]; ++i) { if (!strcmp(className, MissileClassNames[i])) { this->Class = i; break; } } if (!MissileClassNames[i]) { LuaError(l, "Unsupported class: %s" _C_ value); } } else if (!strcmp(value, "NumBounces")) { this->NumBounces = LuaToNumber(l, -1); } else if (!strcmp(value, "Delay")) { this->StartDelay = LuaToNumber(l, -1); } else if (!strcmp(value, "Sleep")) { this->Sleep = LuaToNumber(l, -1); } else if (!strcmp(value, "Speed")) { this->Speed = LuaToNumber(l, -1); } else if (!strcmp(value, "TTL")) { this->TTL = LuaToNumber(l, -1); } else if (!strcmp(value, "Damage")) { this->Damage = LuaToNumber(l, -1); } else if (!strcmp(value, "DrawLevel")) { this->DrawLevel = LuaToNumber(l, -1); } else if (!strcmp(value, "Range")) { this->Range = LuaToNumber(l, -1); } else if (!strcmp(value, "ImpactMissile")) { this->Impact.Name = LuaToString(l, -1); } else if (!strcmp(value, "SmokeMissile")) { this->Smoke.Name = LuaToString(l, -1); } else if (!strcmp(value, "ImpactParticle")) { this->ImpactParticle = new LuaCallback(l, -1); } else if (!strcmp(value, "SmokeParticle")) { this->SmokeParticle = new LuaCallback(l, -1); } else if (!strcmp(value, "CanHitOwner")) { this->CanHitOwner = LuaToBoolean(l, -1); } else if (!strcmp(value, "AlwaysFire")) { this->AlwaysFire = LuaToBoolean(l, -1); } else if (!strcmp(value, "Pierce")) { this->Pierce = LuaToBoolean(l, -1); } else if (!strcmp(value, "PierceOnce")) { this->PierceOnce = LuaToBoolean(l, -1); } else if (!strcmp(value, "FriendlyFire")) { this->FriendlyFire = LuaToBoolean(l, -1); } else if (!strcmp(value, "SplashFactor")) { this->SplashFactor = LuaToNumber(l, -1); } else if (!strcmp(value, "CorrectSphashDamage")) { this->CorrectSphashDamage = LuaToBoolean(l, -1); } else { LuaError(l, "Unsupported tag: %s" _C_ value); } } if (!file.empty()) { this->G = CGraphic::New(file, this->Width(), this->Height()); } }
/** * \brief match the specified luajit * * \param t thread local vars * \param det_ctx pattern matcher thread local data * \param p packet * \param s signature being inspected * \param m sigmatch that we will cast into DetectLuajitData * * \retval 0 no match * \retval 1 match */ static int DetectLuajitMatch (ThreadVars *tv, DetectEngineThreadCtx *det_ctx, Packet *p, Signature *s, SigMatch *m) { SCEnter(); int ret = 0; DetectLuajitData *luajit = (DetectLuajitData *)m->ctx; if (luajit == NULL) SCReturnInt(0); DetectLuajitThreadData *tluajit = (DetectLuajitThreadData *)DetectThreadCtxGetKeywordThreadCtx(det_ctx, luajit->thread_ctx_id); if (tluajit == NULL) SCReturnInt(0); if ((tluajit->flags & DATATYPE_PAYLOAD) && p->payload_len == 0) SCReturnInt(0); if ((tluajit->flags & DATATYPE_PACKET) && GET_PKT_LEN(p) == 0) SCReturnInt(0); if (tluajit->alproto != ALPROTO_UNKNOWN) { if (p->flow == NULL) SCReturnInt(0); FLOWLOCK_RDLOCK(p->flow); int alproto = p->flow->alproto; FLOWLOCK_UNLOCK(p->flow); if (tluajit->alproto != alproto) SCReturnInt(0); } lua_getglobal(tluajit->luastate, "match"); lua_newtable(tluajit->luastate); /* stack at -1 */ if ((tluajit->flags & DATATYPE_PAYLOAD) && p->payload_len) { lua_pushliteral(tluajit->luastate, "payload"); /* stack at -2 */ lua_pushlstring (tluajit->luastate, (const char *)p->payload, (size_t)p->payload_len); /* stack at -3 */ lua_settable(tluajit->luastate, -3); } if ((tluajit->flags & DATATYPE_PACKET) && GET_PKT_LEN(p)) { lua_pushliteral(tluajit->luastate, "packet"); /* stack at -2 */ lua_pushlstring (tluajit->luastate, (const char *)GET_PKT_DATA(p), (size_t)GET_PKT_LEN(p)); /* stack at -3 */ lua_settable(tluajit->luastate, -3); } if (tluajit->alproto == ALPROTO_HTTP) { FLOWLOCK_RDLOCK(p->flow); HtpState *htp_state = p->flow->alstate; if (htp_state != NULL && htp_state->connp != NULL && htp_state->connp->conn != NULL) { int idx = AppLayerTransactionGetInspectId(p->flow); if (idx != -1) { htp_tx_t *tx = NULL; int size = (int)list_size(htp_state->connp->conn->transactions); for ( ; idx < size; idx++) { tx = list_get(htp_state->connp->conn->transactions, idx); if (tx == NULL) continue; if ((tluajit->flags & DATATYPE_HTTP_REQUEST_LINE) && tx->request_line != NULL && bstr_len(tx->request_line) > 0) { lua_pushliteral(tluajit->luastate, "http.request_line"); /* stack at -2 */ lua_pushlstring (tluajit->luastate, (const char *)bstr_ptr(tx->request_line), bstr_len(tx->request_line)); lua_settable(tluajit->luastate, -3); } } } } FLOWLOCK_UNLOCK(p->flow); } int retval = lua_pcall(tluajit->luastate, 1, 1, 0); if (retval != 0) { SCLogInfo("failed to run script: %s", lua_tostring(tluajit->luastate, -1)); } /* process returns from script */ if (lua_gettop(tluajit->luastate) > 0) { /* script returns a number (return 1 or return 0) */ if (lua_type(tluajit->luastate, 1) == LUA_TNUMBER) { double script_ret = lua_tonumber(tluajit->luastate, 1); SCLogDebug("script_ret %f", script_ret); lua_pop(tluajit->luastate, 1); if (script_ret == 1.0) ret = 1; /* script returns a table */ } else if (lua_type(tluajit->luastate, 1) == LUA_TTABLE) { lua_pushnil(tluajit->luastate); const char *k, *v; while (lua_next(tluajit->luastate, -2)) { v = lua_tostring(tluajit->luastate, -1); lua_pop(tluajit->luastate, 1); k = lua_tostring(tluajit->luastate, -1); if (!k || !v) continue; SCLogDebug("k='%s', v='%s'", k, v); if (strcmp(k, "retval") == 0) { if (atoi(v) == 1) ret = 1; } else { /* set flow var? */ } } /* pop the table */ lua_pop(tluajit->luastate, 1); } } if (luajit->negated) { if (ret == 1) ret = 0; else ret = 1; } SCReturnInt(ret); }
/** * Lua specific */ int my_lua_help(lua_State *state) { bool has_sub = false; // implement help() in C so that we do not rely on the init to implement it // help can take optional arguments int n = lua_gettop(state); lua_getglobal(state, "hwstub"); if(!lua_istable(state, -1)) goto Lerr; lua_getfield(state, -1, "help"); if(!lua_istable(state, -1)) goto Lerr; for(int i = 1; i <= n; i++) { lua_pushvalue(state, i); lua_gettable(state, -2); if(lua_isnil(state, -1)) { printf("I don't know subtopic '%s'!\n", lua_tostring(state, i)); return 0; } if(!lua_istable(state, -1)) { printf("Subtopic '%s' is not a table!\n", lua_tostring(state, i)); return 0; } } printf("================[ HELP "); for(int i = 1; i <= n; i++) printf("> %s ", lua_tostring(state, i)); printf("]================\n"); lua_pushnil(state); while(lua_next(state, -2)) { // key is at -2 and value at -1 if(lua_isstring(state, -1)) printf("%s\n", lua_tostring(state, -1)); else if(lua_istable(state, -1)) has_sub = true; // pop value but keep key lua_pop(state, 1); } if(has_sub) { printf("\n"); printf("You can get more information on the following subtopics:\n"); lua_pushnil(state); while(lua_next(state, -2)) { // key is at -2 and value at -1 if(lua_istable(state, -1)) printf("* %s\n", lua_tostring(state, -2)); // pop value but keep key lua_pop(state, 1); } } printf("================[ STOP ]================\n"); return 0; Lerr: printf("There is a problem with the Lua context. Help is expected to be in hwstub.help\n"); printf("You must have messed badly the environment.\n"); return 0; }
static int DetectLuaSetupPrime(DetectLuajitData *ld) { lua_State *luastate = luaL_newstate(); if (luastate == NULL) goto error; luaL_openlibs(luastate); int status = luaL_loadfile(luastate, ld->filename); if (status) { SCLogError(SC_ERR_LUAJIT_ERROR, "couldn't load file: %s", lua_tostring(luastate, -1)); goto error; } /* prime the script (or something) */ if (lua_pcall(luastate, 0, 0, 0) != 0) { SCLogError(SC_ERR_LUAJIT_ERROR, "couldn't prime file: %s", lua_tostring(luastate, -1)); goto error; } lua_getglobal(luastate, "init"); if (lua_type(luastate, -1) != LUA_TFUNCTION) { SCLogError(SC_ERR_LUAJIT_ERROR, "no init function in script"); goto error; } lua_newtable(luastate); /* stack at -1 */ if (lua_gettop(luastate) == 0 || lua_type(luastate, 2) != LUA_TTABLE) { SCLogError(SC_ERR_LUAJIT_ERROR, "no table setup"); goto error; } lua_pushliteral(luastate, "script_api_ver"); /* stack at -2 */ lua_pushnumber (luastate, 1); /* stack at -3 */ lua_settable(luastate, -3); if (lua_pcall(luastate, 1, 1, 0) != 0) { SCLogError(SC_ERR_LUAJIT_ERROR, "couldn't run script 'init' function: %s", lua_tostring(luastate, -1)); goto error; } /* process returns from script */ if (lua_gettop(luastate) == 0) { SCLogError(SC_ERR_LUAJIT_ERROR, "init function in script should return table, nothing returned"); goto error; } if (lua_type(luastate, 1) != LUA_TTABLE) { SCLogError(SC_ERR_LUAJIT_ERROR, "init function in script should return table, returned is not table"); goto error; } lua_pushnil(luastate); const char *k, *v; while (lua_next(luastate, -2)) { v = lua_tostring(luastate, -1); lua_pop(luastate, 1); k = lua_tostring(luastate, -1); if (!k || !v) continue; SCLogDebug("k='%s', v='%s'", k, v); if (strcmp(k, "packet") == 0 && strcmp(v, "true") == 0) { ld->flags |= DATATYPE_PACKET; } else if (strcmp(k, "payload") == 0 && strcmp(v, "true") == 0) { ld->flags |= DATATYPE_PAYLOAD; } else if (strncmp(k, "http", 4) == 0 && strcmp(v, "true") == 0) { if (ld->alproto != ALPROTO_UNKNOWN && ld->alproto != ALPROTO_HTTP) { SCLogError(SC_ERR_LUAJIT_ERROR, "can just inspect script against one app layer proto like HTTP at a time"); goto error; } if (ld->flags != 0) { SCLogError(SC_ERR_LUAJIT_ERROR, "when inspecting HTTP buffers only a single buffer can be inspected"); goto error; } /* http types */ ld->alproto = ALPROTO_HTTP; if (strcmp(k, "http.uri") == 0) ld->flags |= DATATYPE_HTTP_URI; else if (strcmp(k, "http.uri.raw") == 0) ld->flags |= DATATYPE_HTTP_URI_RAW; else if (strcmp(k, "http.request_line") == 0) ld->flags |= DATATYPE_HTTP_REQUEST_LINE; else if (strcmp(k, "http.request_headers") == 0) ld->flags |= DATATYPE_HTTP_REQUEST_HEADERS; else if (strcmp(k, "http.request_headers.raw") == 0) ld->flags |= DATATYPE_HTTP_REQUEST_HEADERS_RAW; else if (strcmp(k, "http.request_cookie") == 0) ld->flags |= DATATYPE_HTTP_REQUEST_COOKIE; else if (strcmp(k, "http.request_user_agent") == 0) ld->flags |= DATATYPE_HTTP_REQUEST_UA; else if (strcmp(k, "http.request_body") == 0) ld->flags |= DATATYPE_HTTP_REQUEST_BODY; else if (strcmp(k, "http.response_body") == 0) ld->flags |= DATATYPE_HTTP_RESPONSE_BODY; else if (strcmp(k, "http.response_cookie") == 0) ld->flags |= DATATYPE_HTTP_RESPONSE_COOKIE; else if (strcmp(k, "http.response_headers") == 0) ld->flags |= DATATYPE_HTTP_RESPONSE_HEADERS; else if (strcmp(k, "http.response_headers.raw") == 0) ld->flags |= DATATYPE_HTTP_RESPONSE_HEADERS_RAW; else { SCLogError(SC_ERR_LUAJIT_ERROR, "unsupported http data type %s", k); goto error; } ld->buffername = SCStrdup(k); if (ld->buffername == NULL) { SCLogError(SC_ERR_LUAJIT_ERROR, "alloc error"); goto error; } } else { SCLogError(SC_ERR_LUAJIT_ERROR, "unsupported data type %s", k); goto error; } } /* pop the table */ lua_pop(luastate, 1); lua_close(luastate); return 0; error: lua_close(luastate); return -1; }
int LuaTableSave::Save() { ACCHECK(lua_istable(m_pLua, -1)); m_objOut << "{"; bool isEmpty = true; lua_pushnil(m_pLua); m_nLayer++; while(lua_next(m_pLua, -2) != 0) { isEmpty = false; PrintTab(); //存储KEY if(lua_type(m_pLua,-2) == LUA_TNUMBER) m_objOut << "[" << lua_tonumber(m_pLua, -2) << "]" << " = "; else if(lua_type(m_pLua, -2) == LUA_TSTRING) m_objOut << lua_tostring(m_pLua, -2) << " = "; else { std::cout << "Unknown key type" << std::endl; ACCHECK(false); } //存储VALUE if(lua_type(m_pLua, -1) == LUA_TNUMBER) m_objOut << lua_tonumber(m_pLua, -1) << ","; else if(lua_type(m_pLua, -1) == LUA_TSTRING) m_objOut << "\"" << lua_tostring(m_pLua, -1) << "\"" << ","; else if(lua_type(m_pLua, -1) == LUA_TBOOLEAN) { int bval = lua_toboolean(m_pLua, -1); std::string strVal = bval ? "true" : "false"; m_objOut << strVal << ","; } else if(lua_type(m_pLua, -1) == LUA_TTABLE) { Save(); } else { std::cout << "Unknown value type" << std::endl; ACCHECK(false); } lua_pop(m_pLua, 1); } m_nLayer--; //层数未达到最大且table不为空,table结束处换行 if((m_nLayer + 1 <= m_nMaxLayer) && (!isEmpty)) PrintTab(); m_objOut << "}"; //不是第一层 if(m_nLayer) m_objOut << ","; return 0; }
int cache_parse_lua(server *srv, connection *con, plugin_data *p, buffer *fn) { lua_State *L; readme rm; int ret = -1; buffer *b; int header_tbl = 0; rm.done = 0; if (-1 == stream_open(&rm.st, fn)) { log_error_write(srv, __FILE__, __LINE__, "sbss", "opening lua cml file ", fn, "failed:", strerror(errno)); return -1; } b = buffer_init(); /* push the lua file to the interpreter and see what happends */ L = luaL_newstate(); luaL_openlibs(L); /* register functions */ lua_register(L, "md5", f_crypto_md5); lua_register(L, "file_mtime", f_file_mtime); lua_register(L, "file_isreg", f_file_isreg); lua_register(L, "file_isdir", f_file_isreg); lua_register(L, "dir_files", f_dir_files); #ifdef HAVE_MEMCACHE_H lua_pushliteral(L, "memcache_get_long"); lua_pushlightuserdata(L, p->conf.mc); lua_pushcclosure(L, f_memcache_get_long, 1); lua_settable(L, LUA_GLOBALSINDEX); lua_pushliteral(L, "memcache_get_string"); lua_pushlightuserdata(L, p->conf.mc); lua_pushcclosure(L, f_memcache_get_string, 1); lua_settable(L, LUA_GLOBALSINDEX); lua_pushliteral(L, "memcache_exists"); lua_pushlightuserdata(L, p->conf.mc); lua_pushcclosure(L, f_memcache_exists, 1); lua_settable(L, LUA_GLOBALSINDEX); #endif /* register CGI environment */ lua_pushliteral(L, "request"); lua_newtable(L); lua_settable(L, LUA_GLOBALSINDEX); lua_pushliteral(L, "request"); header_tbl = lua_gettop(L); lua_gettable(L, LUA_GLOBALSINDEX); c_to_lua_push(L, header_tbl, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri)); c_to_lua_push(L, header_tbl, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path)); c_to_lua_push(L, header_tbl, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(con->physical.path)); c_to_lua_push(L, header_tbl, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.doc_root)); if (!buffer_string_is_empty(con->request.pathinfo)) { c_to_lua_push(L, header_tbl, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo)); } c_to_lua_push(L, header_tbl, CONST_STR_LEN("CWD"), CONST_BUF_LEN(p->basedir)); c_to_lua_push(L, header_tbl, CONST_STR_LEN("BASEURL"), CONST_BUF_LEN(p->baseurl)); /* register GET parameter */ lua_pushliteral(L, "get"); lua_newtable(L); lua_settable(L, LUA_GLOBALSINDEX); lua_pushliteral(L, "get"); header_tbl = lua_gettop(L); lua_gettable(L, LUA_GLOBALSINDEX); buffer_copy_buffer(b, con->uri.query); cache_export_get_params(L, header_tbl, b); buffer_reset(b); /* 2 default constants */ lua_pushliteral(L, "CACHE_HIT"); lua_pushnumber(L, 0); lua_settable(L, LUA_GLOBALSINDEX); lua_pushliteral(L, "CACHE_MISS"); lua_pushnumber(L, 1); lua_settable(L, LUA_GLOBALSINDEX); /* load lua program */ if (lua_load(L, load_file, &rm, fn->ptr) || lua_pcall(L,0,1,0)) { log_error_write(srv, __FILE__, __LINE__, "s", lua_tostring(L,-1)); goto error; } /* get return value */ ret = (int)lua_tonumber(L, -1); lua_pop(L, 1); /* fetch the data from lua */ lua_to_c_get_string(L, "trigger_handler", p->trigger_handler); if (0 == lua_to_c_get_string(L, "output_contenttype", b)) { response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(b)); } if (ret == 0) { /* up to now it is a cache-hit, check if all files exist */ int curelem; time_t mtime = 0; if (!lua_to_c_is_table(L, "output_include")) { log_error_write(srv, __FILE__, __LINE__, "s", "output_include is missing or not a table"); ret = -1; goto error; } lua_pushstring(L, "output_include"); curelem = lua_gettop(L); lua_gettable(L, LUA_GLOBALSINDEX); /* HOW-TO build a etag ? * as we don't just have one file we have to take the stat() * from all base files, merge them and build the etag from * it later. * * The mtime of the content is the mtime of the freshest base file * * */ lua_pushnil(L); /* first key */ while (lua_next(L, curelem) != 0) { stat_cache_entry *sce = NULL; /* key' is at index -2 and value' at index -1 */ if (lua_isstring(L, -1)) { const char *s = lua_tostring(L, -1); /* the file is relative, make it absolute */ if (s[0] != '/') { buffer_copy_buffer(b, p->basedir); buffer_append_string(b, lua_tostring(L, -1)); } else { buffer_copy_string(b, lua_tostring(L, -1)); } if (HANDLER_ERROR == stat_cache_get_entry(srv, con, b, &sce)) { /* stat failed */ switch(errno) { case ENOENT: /* a file is missing, call the handler to generate it */ if (!buffer_string_is_empty(p->trigger_handler)) { ret = 1; /* cache-miss */ log_error_write(srv, __FILE__, __LINE__, "s", "a file is missing, calling handler"); break; } else { /* handler not set -> 500 */ ret = -1; log_error_write(srv, __FILE__, __LINE__, "s", "a file missing and no handler set"); break; } break; default: break; } } else { chunkqueue_append_file(con->write_queue, b, 0, sce->st.st_size); if (sce->st.st_mtime > mtime) mtime = sce->st.st_mtime; } } else { /* not a string */ ret = -1; log_error_write(srv, __FILE__, __LINE__, "s", "not a string"); break; } lua_pop(L, 1); /* removes value'; keeps key' for next iteration */ } lua_settop(L, curelem - 1); if (ret == 0) { data_string *ds; char timebuf[sizeof("Sat, 23 Jul 2005 21:20:01 GMT")]; con->file_finished = 1; ds = (data_string *)array_get_element(con->response.headers, "Last-Modified"); if (0 == mtime) mtime = time(NULL); /* default last-modified to now */ /* no Last-Modified specified */ if (NULL == ds) { strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&mtime)); response_header_overwrite(srv, con, CONST_STR_LEN("Last-Modified"), timebuf, sizeof(timebuf) - 1); ds = (data_string *)array_get_element(con->response.headers, "Last-Modified"); force_assert(NULL != ds); } if (HANDLER_FINISHED == http_response_handle_cachable(srv, con, ds->value)) { /* ok, the client already has our content, * no need to send it again */ chunkqueue_reset(con->write_queue); ret = 0; /* cache-hit */ } } else { chunkqueue_reset(con->write_queue); } } if (ret == 1 && !buffer_string_is_empty(p->trigger_handler)) { /* cache-miss */ buffer_copy_buffer(con->uri.path, p->baseurl); buffer_append_string_buffer(con->uri.path, p->trigger_handler); buffer_copy_buffer(con->physical.path, p->basedir); buffer_append_string_buffer(con->physical.path, p->trigger_handler); chunkqueue_reset(con->write_queue); } error: lua_close(L); stream_close(&rm.st); buffer_free(b); return ret /* cache-error */; }
int check_daoack(lua_State *L) { lua_pushlightfunction(L, libmsgpack_mp_unpack); lua_pushvalue(L, lua_upvalueindex(1)); lua_call(L, 1, 1); int t_idx=lua_gettop(L); lua_pushstring(L, "dest"); lua_gettable(L, t_idx); char *d_ip= (char *)lua_tostring(L, -1); lua_getglobal(L, "DAO_ACK"); int dt_idx=lua_gettop(L); lua_pushstring(L, -2); //ip address of required destination lua_gettable(L, -2); if(isnil(L, -1)) //No dao_ack for this ip addr { lua_getglobal(L, "PFLAG"); int pflag = lua_tonumber(L, -1); if(pflag > 5) //more than 5 retransmissions already occured to this parent { //Parent is dead, find new parent lua_getglobal(L, "parent_table"); int p_idx=lua_gettop(L); lua_pushnil(L); if(lua_next(L, p_idx)==0) // no elements in the parent table { //send poisoning DIO to release all children //rebroadcast DIS //reinitialise dio, dis, all tables } else { //IP Addr of next parent is at index -2 char *p_ip = (char *)lua_tostring(L, -2); int p_rank = lua_tonumber(L, -1); //rank of new parent lua_pop(L, 1); //now Parent IP is on top of the stack (after popping rank) lua_setglobal(L, "PrefParent"); //remove node from parent table lua_pushstring(L, p_ip); int ref = luaL_ref (L, p_idx); luaL_unref(L, p_idx, ref); //remove all nodes from parent table whose rank is less than new rank lua_pushnil(L); while(lua_next(L, p_idx)!=0) { if(lua_tonumber(L, -1) > p_rank) { lua_pushvalue(L, -2); // srcip (key) of next parent) ref = luaL_ref (L, p_idx); luaL_unref(L, p_idx, ref); //remove entry from table //lua_pop(L, 1); //if lua_unref does not pop reference from top of the stack } lua_pop(L, 1); } //send dis to preferred parent, wait for DIO lua_pushlightfunction(L, libstorm_net_sendto); lua_getglobal(L,"diomcast_sock"); lua_pushlightfunction(L, libmsgpack_mp_pack); lua_getglobal(L, "DIS"); lua_call(L, 1, 1); lua_pushstring(L, p_ip); lua_pushnumber(L, disrecvport); lua_call(L, 4, 1); //send new DAO all the way to the root with your own information } lua_pushnumber(L, 0); lua_setglobal(L, "PFLAG"); return 0; } lua_pushnumber(L, pflag + 1); lua_setglobal(L, "PFLAG"); lua_pushlightfunction(L, send_dao); lua_pushvalue(L, 1); //push the packed prefix table onto the stack lua_call(L, 1, 0); } else //ACK Received, no need to call send again, remove DAO_ACK from table { lua_pushstring(L, d_ip); int ref = luaL_ref (L, p_idx); luaL_unref(L, p_idx, ref); lua_pushvalue(L, dt_idx); lua_setglobal(L, "DAO_ACK"); lua_pushnumber(L, 0); lua_setglobal(L, "PFLAG"); //Parent flag, to check if prefparent is alive } return 0; }
/** ** Define the sprite to show variables. ** ** @param l Lua_state */ static int CclDefineSprites(lua_State *l) { const char *name; // name of the current sprite. int args; // number of arguments. int i; // iterator on argument. const char *key; // Current key of the lua table. int index; // Index of the Sprite. args = lua_gettop(l); for (i = 0; i < args; ++i) { Decoration deco; lua_pushnil(l); name = 0; while (lua_next(l, i + 1)) { key = LuaToString(l, -2); // key name if (!strcmp(key, "Name")) { name = LuaToString(l, -1); } else if (!strcmp(key, "File")) { deco.File = LuaToString(l, -1); } else if (!strcmp(key, "Offset")) { if (!lua_istable(l, -1) || luaL_getn(l, -1) != 2) { LuaError(l, "incorrect argument"); } lua_rawgeti(l, -1, 1); // offsetX lua_rawgeti(l, -2, 2); // offsetY deco.HotX = LuaToNumber(l, -2); deco.HotY = LuaToNumber(l, -1); lua_pop(l, 2); // Pop offsetX and Y } else if (!strcmp(key, "Size")) { if (!lua_istable(l, -1) || luaL_getn(l, -1) != 2) { LuaError(l, "incorrect argument"); } lua_rawgeti(l, -1, 1); // Width lua_rawgeti(l, -2, 2); // Height deco.Width = LuaToNumber(l, -2); deco.Height = LuaToNumber(l, -1); lua_pop(l, 2); // Pop Width and Height } else { // Error. LuaError(l, "incorrect field '%s' for the DefineSprite." _C_ key); } lua_pop(l, 1); // pop the value; } if (name == 0) { LuaError(l, "CclDefineSprites requires the Name flag for sprite."); } index = GetSpriteIndex(name); if (index == -1) { // new sprite. index = DecoSprite.SpriteArray.size(); DecoSprite.Name.push_back(new_strdup(name)); DecoSprite.SpriteArray.push_back(deco); } else { DecoSprite.SpriteArray[index].File.clear(); DecoSprite.SpriteArray[index] = deco; } // Now verify validity. if (DecoSprite.SpriteArray[index].File.empty()) { LuaError(l, "CclDefineSprites requires the File flag for sprite."); } // FIXME check if file is valid with good size ? } return 0; }
//box[], particles[], shapes[] static int luaScene_load(lua_State* L){ SimConfig config; for(lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)){ long long int i = lua_tointeger(L, -2) - 1; if(i < 0 || i >= 9){ fprintf(stderr, "Invalid index for box table encountered while loading scene.\n"); return 0; } config.box[i % 3][i / 3] = lua_tonumber(L, -1); } config.n_particles = lua_rawlen(L, 2); config.particles = new Particle[config.n_particles]; size_t pid = 0; for(lua_pushnil(L); lua_next(L, 2);){ config.particles[pid++] = maan::get_LuaValue<Particle>(L); } config.n_shapes = lua_rawlen(L, 3); config.shapes = new Shape[config.n_shapes]; //TODO: Add a is_class(lua_State* L, int idx) function to maan. size_t sid = 0; for(lua_pushnil(L); lua_next(L, 3);){ if(!lua_isuserdata(L, -1)){ fprintf(stderr, "Unknown item type encountered in shapes table while loading scene. 'Shape' expected, got '%s'.\n", luaL_typename(L, -1)); delete[] config.particles; delete[] config.shapes; return 0; } lua_getmetatable(L, -1); lua_pushstring(L, "__class_id"); lua_rawget(L, -2); if(lua_isnil(L, -1)){ fprintf(stderr, "Unknown userdata type encountered in shapes table while loading scene.\n"); delete[] config.particles; delete[] config.shapes; return 0; } void* class_id = lua_touserdata(L, -1); lua_pop(L, 2); auto shape = Shape(); if(maan::detail::ClassInfo<Sphere>::get_metatable_key() == class_id){ shape.type = Shape::SPHERE; lua_pop(L, 1); } else if(maan::detail::ClassInfo<Mesh>::get_metatable_key() == class_id){ shape.type = Shape::MESH; auto mesh = maan::get_LuaValue<Mesh>(L); shape.mesh.n_vertices = mesh.vertices_.size(); shape.mesh.vertices = new Vertex[shape.mesh.n_vertices]; int i = 0; for(auto vertex: mesh.vertices_){ shape.mesh.vertices[i++] = vertex; } } else{ lua_getmetatable(L, -1); lua_pushstring(L, "__name"); lua_rawget(L, -2); fprintf(stderr, "Unknown class type encountered in shapes table while loading scene. 'Shape' expected, got '%s'.\n", lua_tostring(L, -1)); lua_pop(L, 2); delete[] config.particles; delete[] config.shapes; return 0; } config.shapes[sid++] = shape; } auto scene = reinterpret_cast<Scene*>(lua_touserdata(L, lua_upvalueindex(1))); scene->load_scene(config); delete[] config.particles; delete[] config.shapes; return 0; }
int plugin_debug_con_handle_stmt(chassis *chas, network_mysqld_con *con, GString *s) { gsize i, j; GPtrArray *fields; GPtrArray *rows; GPtrArray *row; switch(s->str[NET_HEADER_SIZE]) { case COM_QUERY: fields = NULL; rows = NULL; row = NULL; /* support the basic commands sent by the mysql shell */ if (0 == g_ascii_strncasecmp(s->str + NET_HEADER_SIZE + 1, C("select @@version_comment limit 1"))) { MYSQL_FIELD *field; fields = network_mysqld_proto_fielddefs_new(); field = network_mysqld_proto_fielddef_new(); field->name = g_strdup("@@version_comment"); field->type = FIELD_TYPE_VAR_STRING; g_ptr_array_add(fields, field); rows = g_ptr_array_new(); row = g_ptr_array_new(); g_ptr_array_add(row, g_strdup("MySQL Enterprise Agent")); g_ptr_array_add(rows, row); network_mysqld_con_send_resultset(con->client, fields, rows); } else if (0 == g_ascii_strncasecmp(s->str + NET_HEADER_SIZE + 1, C("select USER()"))) { MYSQL_FIELD *field; fields = network_mysqld_proto_fielddefs_new(); field = network_mysqld_proto_fielddef_new(); field->name = g_strdup("USER()"); field->type = FIELD_TYPE_VAR_STRING; g_ptr_array_add(fields, field); rows = g_ptr_array_new(); row = g_ptr_array_new(); g_ptr_array_add(row, g_strdup("root")); g_ptr_array_add(rows, row); network_mysqld_con_send_resultset(con->client, fields, rows); } else { MYSQL_FIELD *field = NULL; lua_State *L = chas->priv->sc->L; if (0 == luaL_loadstring(L, s->str + NET_HEADER_SIZE + 1) && 0 == lua_pcall(L, 0, 1, 0)) { /* let's see what is on the stack * - scalars are turned into strings * return "foo" * - 1-dim tables are turned into a single-row result-set * return { foo = "bar", baz = "foz" } * - 2-dim tables are turned into a multi-row result-set * return { { foo = "bar" }, { "foz" } } */ switch (lua_type(L, -1)) { case LUA_TTABLE: /* take the names from the fields */ fields = network_mysqld_proto_fielddefs_new(); lua_pushnil(L); while (lua_next(L, -2) != 0) { if (lua_istable(L, -1)) { /* 2-dim table * * we only only take the keys from the first row * afterwards we ignore them */ lua_pushnil(L); while (lua_next(L, -2) != 0) { if (!rows) { /* this is the 1st round, add the keys */ lua_table_key_to_mysql_field(L, fields); } if (!row) row = g_ptr_array_new(); if (lua_isboolean(L, -1)) { g_ptr_array_add(row, g_strdup(lua_toboolean(L, -1) ? "TRUE" : "FALSE")); } else if (lua_isnumber(L, -1)) { g_ptr_array_add(row, g_strdup_printf("%.0f", lua_tonumber(L, -1))); } else { g_ptr_array_add(row, g_strdup(lua_tostring(L, -1))); } lua_pop(L, 1); /* pop the value, but keep the key on the stack */ } if (!rows) rows = g_ptr_array_new(); g_ptr_array_add(rows, row); row = NULL; } else { /* 1-dim table */ lua_table_key_to_mysql_field(L, fields); if (!row) row = g_ptr_array_new(); if (lua_isboolean(L, -1)) { g_ptr_array_add(row, g_strdup(lua_toboolean(L, -1) ? "TRUE" : "FALSE")); } else if (lua_isnumber(L, -1)) { g_ptr_array_add(row, g_strdup_printf("%.0f", lua_tonumber(L, -1))); } else { g_ptr_array_add(row, g_strdup(lua_tostring(L, -1))); } } lua_pop(L, 1); /* pop the value, but keep the key on the stack */ } if (row) { /* in 1-dim we have to append the row to the result-set, * in 2-dim this is already done and row is NULL */ if (!rows) rows = g_ptr_array_new(); g_ptr_array_add(rows, row); } break; default: /* a scalar value */ fields = network_mysqld_proto_fielddefs_new(); field = network_mysqld_proto_fielddef_new(); field->name = g_strdup("lua"); field->type = FIELD_TYPE_VAR_STRING; g_ptr_array_add(fields, field); rows = g_ptr_array_new(); row = g_ptr_array_new(); g_ptr_array_add(row, g_strdup(lua_tostring(L, -1))); g_ptr_array_add(rows, row); break; } lua_pop(L, 1); /* get rid of the result */ network_mysqld_con_send_resultset(con->client, fields, rows); } /* if we don't have fields for the resultset, we should have a * error-msg on the stack */ if (!fields) { size_t err_len = 0; const char *err; err = lua_tolstring(L, -1, &err_len); network_mysqld_con_send_error(con->client, err, err_len); lua_pop(L, 1); } } /* clean up */ if (fields) { network_mysqld_proto_fielddefs_free(fields); fields = NULL; } if (rows) { for (i = 0; i < rows->len; i++) { row = rows->pdata[i]; for (j = 0; j < row->len; j++) { g_free(row->pdata[j]); } g_ptr_array_free(row, TRUE); } g_ptr_array_free(rows, TRUE); rows = NULL; } break; case COM_QUIT: break; case COM_INIT_DB: network_mysqld_con_send_ok(con->client); break; default: network_mysqld_con_send_error(con->client, C("unknown COM_*")); break; } return 0; }
bool sinsp_chisel::parse_view_info(lua_State *ls, OUT chisel_desc* cd) { lua_getglobal(ls, "view_info"); if(lua_isnoneornil(ls, -1)) { lua_close(ls); return false; } lua_pushnil(ls); string tmpstr; string id; string name; string description; vector<string> applies_to; string filter; bool use_defaults = false; sinsp_view_info::viewtype vt = sinsp_view_info::T_TABLE; vector<sinsp_view_column_info> columns; vector<string> tags; vector<string> tips; string drilldown_target; bool is_root = false; while(lua_next(ls, -2) != 0) { string fldname = lua_tostring(ls, -2); if(fldname == "name") { name = lua_tostring(ls, -1); } else if(fldname == "id") { id = lua_tostring(ls, -1); } else if(fldname == "description") { description = lua_tostring(ls, -1); } else if(fldname == "tags") { if(lua_istable(ls, -1)) { lua_pushnil(ls); while(lua_next(ls, -2) != 0) { if(lua_isstring(ls, -1)) { tmpstr = lua_tostring(ls, -1); tags.push_back(tmpstr); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + "tags entries must be strings"); } lua_pop(ls, 1); } } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table"); } } else if(fldname == "tips") { if(lua_istable(ls, -1)) { lua_pushnil(ls); while(lua_next(ls, -2) != 0) { if(lua_isstring(ls, -1)) { tmpstr = lua_tostring(ls, -1); tips.push_back(tmpstr); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + "tips column entries must be strings"); } lua_pop(ls, 1); } } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table"); } } else if(fldname == "view_type") { tmpstr = lua_tostring(ls, -1); if(tmpstr == "table") { vt = sinsp_view_info::T_TABLE; } else if(tmpstr == "list") { vt = sinsp_view_info::T_LIST; } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " must be either 'table' or 'list'"); } } else if(fldname == "drilldown_target") { drilldown_target = lua_tostring(ls, -1); } else if(fldname == "applies_to") { if(lua_istable(ls, -1)) { lua_pushnil(ls); while(lua_next(ls, -2) != 0) { if(lua_isstring(ls, -1)) { tmpstr = lua_tostring(ls, -1); applies_to.push_back(tmpstr); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + "tips column entries must be strings"); } lua_pop(ls, 1); } } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table"); } } else if(fldname == "filter") { filter = lua_tostring(ls, -1); } else if(fldname == "use_defaults") { if(lua_isboolean(ls, -1)) { use_defaults = (lua_toboolean(ls, -1) != 0); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " must be a boolean"); } } else if(fldname == "is_root") { if(lua_isboolean(ls, -1)) { is_root = (lua_toboolean(ls, -1) != 0); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " must be a boolean"); } } else if(fldname == "columns") { if(lua_istable(ls, -1)) { parse_view_columns(ls, cd, &columns); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table"); } } lua_pop(ls, 1); } cd->m_viewinfo = sinsp_view_info(vt, id, name, description, tags, tips, columns, applies_to, filter, drilldown_target, use_defaults, is_root); return true; }
bool Settings::save() { auto& actions = m_app.getActions(); Lumix::FS::OsFile file; auto& allocator = m_app.getWorldEditor()->getAllocator(); if (!file.open(SETTINGS_PATH, Lumix::FS::Mode::CREATE_AND_WRITE, allocator)) return false; file << "window = { x = " << m_window.x << ", y = " << m_window.y << ", w = " << m_window.w << ", h = " << m_window.h << " }\n"; file << "maximized = " << (m_is_maximized ? "true" : "false") << "\n"; auto writeBool = [&file](const char* name, bool value) { file << name << " = " << (value ? "true\n" : "false\n"); }; writeBool("settings_opened", m_is_opened); writeBool("asset_browser_opened", m_is_asset_browser_opened); writeBool("entity_list_opened", m_is_entity_list_opened); writeBool("entity_template_list_opened", m_is_entity_template_list_opened); writeBool("log_opened", m_is_log_opened); writeBool("profiler_opened", m_is_profiler_opened); writeBool("properties_opened", m_is_properties_opened); writeBool("error_reporting_enabled", m_is_crash_reporting_enabled); file << "mouse_sensitivity_x = " << m_mouse_sensitivity_x << "\n"; file << "mouse_sensitivity_y = " << m_mouse_sensitivity_y << "\n"; saveStyle(file); file << "data_dir = \""; const char* c = m_data_dir; while (*c) { if (*c == '\\') file << "\\\\"; else file << *c; ++c; } file << "\"\n"; file << "custom = {\n"; lua_getglobal(m_state, "custom"); lua_pushnil(m_state); bool first = true; while (lua_next(m_state, -2)) { if (!first) file << ",\n"; const char* name = lua_tostring(m_state, -2); switch (lua_type(m_state, -1)) { case LUA_TBOOLEAN: file << name << " = " << (lua_toboolean(m_state, -1) != 0 ? "true" : "false"); break; case LUA_TNUMBER: file << name << " = " << (int)lua_tonumber(m_state, -1); break; default: ASSERT(false); break; } lua_pop(m_state, 1); first = false; } lua_pop(m_state, 1); file << "}\n"; file << "actions = {\n"; for (int i = 0; i < actions.size(); ++i) { file << "\t" << actions[i]->name << " = {" << actions[i]->shortcut[0] << ", " << actions[i]->shortcut[1] << ", " << actions[i]->shortcut[2] << "},\n"; } file << "}\n"; file << "toolbar = {\n"; for (auto* action : m_app.getToolbarActions()) { file << "\t\"" << action->name << "\",\n"; } file << "}\n"; ImGui::SaveDock(file); file.close(); return true; }
static liValue* li_value_from_lua_table(liServer *srv, lua_State *L, int ndx) { liValue *val = NULL, *sub_option; GArray *list = NULL; GHashTable *hash = NULL; int ikey; GString *skey; ndx = li_lua_fixindex(L, ndx); lua_pushnil(L); while (lua_next(L, ndx) != 0) { switch (lua_type(L, -2)) { case LUA_TNUMBER: if (hash) goto mixerror; if (!list) { val = li_value_new_list(); list = val->data.list; } ikey = lua_tointeger(L, -2) - 1; if (ikey < 0) { ERROR(srv, "Invalid key < 0: %i - skipping entry", ikey + 1); lua_pop(L, 1); continue; } sub_option = li_value_from_lua(srv, L); if (!sub_option) continue; if ((size_t) ikey >= list->len) { g_array_set_size(list, ikey + 1); } g_array_index(list, liValue*, ikey) = sub_option; break; case LUA_TSTRING: if (list) goto mixerror; if (!hash) { val = li_value_new_hash(); hash = val->data.hash; } skey = li_lua_togstring(L, -2); if (g_hash_table_lookup(hash, skey)) { ERROR(srv, "Key already exists in hash: '%s' - skipping entry", skey->str); lua_pop(L, 1); continue; } sub_option = li_value_from_lua(srv, L); if (!sub_option) { g_string_free(skey, TRUE); continue; } g_hash_table_insert(hash, skey, sub_option); break; default: ERROR(srv, "Unexpted key type in table: %s (%i) - skipping entry", lua_typename(L, -1), lua_type(L, -1)); lua_pop(L, 1); break; } } return val; mixerror: ERROR(srv, "%s", "Cannot mix list with hash; skipping remaining part of table"); lua_pop(L, 2); return val; }
bool TileType::loadStandardTileTypesLua(const char *filename) { LuaState lua(false); if (!lua.loadFile(filename)) { lua.logStack("TITLE"); lua.close(); stringstream errss; errss << "Unable to load standard tile types"; am_log("TILE", errss); return false; } lua_getglobal(lua, "types"); if (!lua_istable(lua, -1)) { stringstream errss; errss << "Unable to load standard tile types, loaded file was of type: " << lua_typename(lua, -1); am_log("TILE", errss); lua.close(); return false; } /* table is in the stack at index 't' */ lua_pushnil(lua); /* first key */ while (lua_next(lua, -2) != 0) { /* uses 'key' (at index -2) and 'value' (at index -1) */ if (lua_isstring(lua, -2)) { if (!lua_istable(lua, -1)) { stringstream errss; errss << "Tile type '" << lua_tostring(lua, -2) << "' was of type '" << lua_typename(lua, -1) << "' and not an object."; am_log("TILE", errss); continue; } string tileName = Utils::toLowerCase(lua_tostring(lua, -2)); TileType *loadedType = new TileType(tileName.c_str()); if (!loadedType->loadFromDef(lua)) { stringstream errss; errss << "Failed to load '" << tileName << "' object in definition was invalid."; am_log("TILE", errss); delete loadedType; continue; } stringstream ss; ss << "Added tile type '" << loadedType->getName() << "'"; am_log("TILE", ss); // TODO: Change to not needing this loadStandard function. Engine::getEngine()->addTileType(loadedType); } /* removes 'value'; keeps 'key' for next iteration */ lua_pop(lua, 1); } lua.close(); return true; }