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

时间:2013-12-04 16:08:36

标签: c++ lua lua-5.2

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

这是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:'尝试调用nil值'。

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

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

我误解了什么吗?

2 个答案:

答案 0 :(得分:4)

luaL_loadfile只是加载文件,它不会运行它。请改为luaL_dofile

您仍然会收到错误,因为print是在基本库中定义的,而不是在io库中定义的。所以请改为呼叫luaopen_base

答案 1 :(得分:1)

您需要致电" priming lua_pacll()"在lua_getglobal()之前。请参考Calling Lua From a C Program。整个代码应该是这样的:

int iErr = 0;

//Create a lua state
lua_State *lua = luaL_newstate();

// Load base library
luaopen_base (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");

    //Call priming lua_pcall
    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));
    }

    // 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);