问题描述
我有下面的代码:
lua_State *lua;
lua = lua_open();
luaL_openlibs(lua);
std::string code = "print(gvar)\n"
"function test()\n"
"print(gvar)\n"
"end\n";
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);
}
}
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);
}
lua_close(lua);
调用函数并获取全局变量很好,但是当我尝试设置全局变量时,调用nil值。我不明白为什么是这样?
Calling functions and getting global variables works fine, but when i try to set global variable i get "attempt to call a nil value". And i cant understand why is that?
推荐答案
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>,但是栈是空的 - 这就是为什么你得到
尝试调用一个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.
这篇关于c ++ lua设置全局变量时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!