6

我在获取从 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 代码的示例,但似乎看不出我哪里出错了。这看起来绝对应该有效(根据我读过的内容)。

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

我是不是误会了什么???

4

2 回答 2

4

luaL_loadfile只是加载文件,它不运行它。试试luaL_dofile吧。

你仍然会得到一个错误,因为print是在基础库中定义的,而不是在 io 库中。所以luaopen_base改为打电话。

于 2013-12-04T16:32:22.043 回答
2

你需要先调用" priming lua_pacll()" lua_getglobal()。请参阅从 C 程序调用 Lua。整个代码应该是这样的:

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);
于 2015-07-03T02:23:58.343 回答