簡體   English   中英

Lua 5.2問題:'嘗試從lua_pcall調用一個nil值'

[英]Lua 5.2 issue: 'attempt to call a nil value' from lua_pcall

我在使用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代碼的例子,似乎無法看到我出錯的地方。 這看起來應該絕對有效(根據我讀過的內容)。

我檢查了拼寫和區分大小寫,這一切都匹配了。

我誤解了什么嗎???

luaL_loadfile只是加載文件,它不會運行它。 請嘗試luaL_dofile

您仍然會收到錯誤,因為print是在基本庫中定義的,而不是在io庫中定義的。 所以請調用luaopen_base

你需要在lua_getglobal()之前調用“ priming lua_pacll() ”。 請參考C程序中的Calling 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM