Lua 5.2问题:lua_pcall中的'试图调用nil值' [英] Lua 5.2 issue: 'attempt to call a nil value' from lua_pcall
问题描述
我在从C ++调用Lua 5.2函数时遇到问题.
I'm having problems getting a Lua 5.2 function to get called from C++.
这是Lua块(名为test.lua):
This is the Lua chunk (named 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.
When I trace, I see that it loads the test.lua script fine (no error is returned), it then shows that the stack height is 3 after calling the lua_getglobal with the function name.
但是,它在lua_pcall上失败,错误代码2:试图调用nil值".
However, it fails at lua_pcall with the error code 2: 'attempt to call a nil value'.
我已经阅读了很多Lua 5.2代码的示例,似乎看不到我要去哪里. 看来它确实应该工作(根据我所读的内容).
I've read plenty of examples of Lua 5.2 code, and can't seem to see where I'm going wrong. This looks like it should definitely work (according to what I've read).
我已经检查了拼写和区分大小写,并且都匹配了.
I've checked spelling and case sensitivity, and it all matches up.
我误解了吗?
推荐答案
luaL_loadfile
只是加载文件,不会运行它.尝试使用luaL_dofile
.
luaL_loadfile
just loads the file, it does not run it. Try luaL_dofile
instead.
您仍然会收到错误消息,因为print
是在基础库中定义的,而不是在io库中定义的.因此,请致电luaopen_base
.
You'll still get an error because print
is defined in the base library, not in the io library. So call luaopen_base
instead.
这篇关于Lua 5.2问题:lua_pcall中的'试图调用nil值'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!