In our menu system, we define menus in xml with lua chunks used for callbacks for menu component events. Currently, everytime a script callback is called, we call lua_loadstring which is quite slow. I'm trying to make it so this only happens once, when the menu is loaded.
My initial thought was to maintain a lua table per menu component and to do the following to add a new callback function to the table:
//create lua code that will assign a function to our table
std::string callback = "temp." + callbackName + " = function (" + params + ")" + luaCode + "end";
//push table onto stack
lua_rawgeti(L, LUA_REGISTRYINDEX, luaTableRef_);
//pop table from stack and set it as value of global "temp"
lua_setglobal(L, "temp");
//push new function onto stack
int error = luaL_loadstring(L, callback.c_str());
if ( error )
{
const char* errorMsg = lua_tostring(L, -1);
Dbg::Printf("error loading the script '%s' : %s\n", callbackName, errorMsg);
lua_pop(L,1);
return;
}
//call the lua code to insert the loaded function into the global temp table
if (lua_pcall(L, 0, 0, 0))
{
Dbg::Printf("luascript: error running the script '%s'\n", lua_tostring(L, -1));
lua_pop(L, 1);
}
//table now has function in it
This seems kind of dirty. Is there a better way that allows me to assign the function to the table directly from a lua chunk without having to use a temp global variable and running lua_pcall?