gpt4 book ai didi

c++ - 为菜单系统实现 lua 回调

转载 作者:搜寻专家 更新时间:2023-10-31 01:55:58 24 4
gpt4 key购买 nike

在我们的菜单系统中,我们使用 lua block 在 xml 中定义菜单,用于菜单组件事件的回调。目前,每次调用脚本回调时,我们都会调用 lua_loadstring,这非常慢。我试图做到这一点,所以这只会在加载菜单时发生一次。

我最初的想法是为每个菜单组件维护一个 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 block 将函数分配给表,而不必使用临时全局变量和运行 lua_pcall?

最佳答案

如果要把函数放在表里,那就把函数放在表里。看来你的lua-stack-fu不强;考虑 studying the manual a bit more closely .

无论如何,我想说您遇到的最大问题是您对params 的坚持。回调函数应该是可变的;他们将 ... 作为参数。如果他们想获得这些值,他们应该像这样使用本地人:

local param1, param2 = ...;

但是如果你坚持让他们指定一个参数列表,你可以这样做:

std::string luaChunk =
//The ; is here instead of a \n so that the line numbering
//won't be broken by the addition of this code.
"local " + params + " = ...; " +
luaCode;

lua_checkstack(L, 3);
lua_rawgeti(L, LUA_REGISTRYINDEX, luaTableRef_);
if(lua_isnil(L, -1))
{
//Create the table if it doesn't already exist.
lua_newtable(L);

//Put it in the registry.
lua_rawseti(L, LUA_REGISTRYINDEX, luaTableRef_);

//Get it back, since setting it popped it.
lua_rawgeti(L, LUA_REGISTRYINDEX, luaTableRef_);
}

//The table is on the stack. Now put the key on the stack.
lua_pushlstring(L, callbackName.c_str(), callbackName.size());

//Load up our function.
int error = luaL_loadbuffer(L, luaChunk.c_str(), luaChunk.size(),
callbackName.c_str());
if( error )
{
const char* errorMsg = lua_tostring(L, -1);
Dbg::Printf("error loading the script '%s' : %s\n", callbackName, errorMsg);
//Pop the function name and the table.
lua_pop(L, 2);
return;
}

//Put the function in the table.
lua_settable(L, -3);

//Remove the table from the stack.
lua_pop(L, 1);

关于c++ - 为菜单系统实现 lua 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7812801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com