2
在我們的菜單系統中,我們使用用於菜單組件事件回調的lua塊來定義xml菜單。目前,每次調用腳本回調函數時,都會調用lua_loadstring,這很慢。我試圖做到這一點,所以這隻會發生一次,當菜單加載。爲菜單系統實現lua回調
我最初的想法是保持每個菜單組件一個Lua表,並做到以下幾點到一個新的回調函數添加到表:
//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
這似乎有點髒。有沒有更好的方法,允許我直接從lua塊中將函數分配給表,而無需使用臨時全局變量並運行lua_pcall?
感謝清理起來。我會用「...」 – brunoma