我在获取从 C++ 调用的 Lua 5.2 函数时遇到问题。
这是 Lua 块(名为 test.lua):
function testFunction ()
print "Hello World"
end
这是C++:
int iErr = 0;
//Create a lua state
lua_State *lua = luaL_newstate();
// Load io library
luaopen_io (lua);
//load the chunk we want to execute (test.lua)
iErr = luaL_loadfile(lua, "test.lua");
if (iErr == 0) {
printf("successfully loaded test.lua\n");
// Push the function name onto the stack
lua_getglobal(lua, "testFunction");
printf("called lua_getglobal. lua stack height is now %d\n", lua_gettop(lua));
//Call our function
iErr = lua_pcall(lua, 0, 0, 0);
if (iErr != 0) {
printf("Error code %i attempting to call function: '%s'\n", iErr, lua_tostring(lua, -1));
}
} else {
printf("Error loading test.lua. Error code: %s\n", lua_tostring(lua, -1));
}
lua_close (lua);
当我跟踪时,我看到它很好地加载了 test.lua 脚本(没有返回错误),然后显示在使用函数名调用 lua_getglobal 后堆栈高度为 3。
但是,它在 lua_pcall 处失败,错误代码为 2:'attempt to call a nil value'。
我已经阅读了大量 Lua 5.2 代码的示例,但似乎看不出我哪里出错了。这看起来绝对应该有效(根据我读过的内容)。
我检查了拼写和区分大小写,一切都匹配。
我是不是误会了什么???