且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

c ++ lua设置全局变量时出错

更新时间:2023-02-04 08:48:13

if(!luaL_loadstring(lua, code.c_str())){
    if (lua_pcall(lua, 0, 0, 0)){
        const char* error = lua_tostring(lua, -1); 
        lua_pop(lua, 1);
    }
}

此代码将字符串加载到匿名函数中使用 luaL_loadstring(),将它放在堆栈上,然后使用 lua_pcall(lua,0,0,0)执行函数。

This code loads string into a anonymous function using luaL_loadstring(), puts it on the stack and then executes the function using lua_pcall(lua, 0, 0, 0).

lua_pushstring(lua, "100");
lua_setglobal(lua, "gvar");
if (lua_pcall(lua, 0, 0, 0)){
    const char* error = lua_tostring(lua, -1); // returns "attempt to call a nil value"
    lua_pop(lua, 1);
}

这段代码将字符串推入堆栈,然后设置全局变量 gvar 。在调用 lua_setglobal()后,堆栈上应该没有任何东西。

This piece of code pushes string onto the stack then sets global variable gvar. There should be nothing on the stack after call to lua_setglobal(). The var is already there.

现在,您尝试使用 lua_pcall $ c>调用位于堆栈顶部的函数$ c>,但是栈是空的 - 这就是为什么你得到尝试调用一个nil值消息。

Now after that you try to call a function which is at the top of the stack with lua_pcall, but the stack is empty - that's why you get attempt to call a nil value message.