Lua 5.2问题:'尝试从lua_pcall调用一个nil值'

use*_*503 6 c++ lua lua-5.2

我在使用Lua 5.2函数从C++调用时遇到了问题.

这是Lua块(名为test.lua):

function testFunction ()
print "Hello World"
end
Run Code Online (Sandbox Code Playgroud)

这是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);
Run Code Online (Sandbox Code Playgroud)

当我跟踪时,我看到它正好加载test.lua脚本(没有返回错误),然后在使用函数名称调用lua_getglobal后显示堆栈高度为3.

但是,它在lua_pcall失败,错误代码为2:'尝试调用nil值'.

我已经阅读了很多Lua 5.2代码的例子,似乎无法看到我出错的地方.这看起来应该绝对有效(根据我读过的内容).

我检查了拼写和区分大小写,这一切都匹配了.

我误解了什么吗???

lhf*_*lhf 4

luaL_loadfile只是加载文件,并不运行它。尝试luaL_dofile一下。

您仍然会收到错误,因为print是在基础库中定义的,而不是在 io 库中。所以还是打电话luaopen_base吧。