簡體   English   中英

如何使用Lua c API正確讀取字符串和表參數?

[英]How to properly read string and table arguments with Lua c API?

我花了幾個小時試圖使其無法成功運行。 我有一個C ++程序,其功能公開給Lua腳本。 Lua腳本像這樣使用它:

    setData('type', {a=1, b=2, c=3})

因此,第一個參數是字符串,第二個參數是表。

我當前和最好的C ++ setData函數版本如下所示:

    string sType;
    map<string, uint8_t> mOptions;

    int nArgs = lua_gettop(i_pState);
    if (nArgs == 2)
    {
        if (lua_isstring(i_pState, 1) != 0)
            sType = lua_tostring(i_pState, 1);

        if (lua_istable(i_pState, 2) != 0)
        {
            lua_pushnil(i_pState);
            while(lua_next(i_pState, 2))
            {
                uint8_t nValue = uint8_t(lua_tonumber(i_pState, -1));
                string  sKey   = lua_tostring(i_pState, -2);

                mOptions[sKey] = nValue;

                lua_pop(i_pState, 1);
            }
            lua_pop(i_pState, 1);
        }
    }

    return 0;

它工作正常,但隨后在調用lua_close()函數時最終導致“ program.exe觸發了斷點”錯誤。 此代碼有什么問題?

UPD1。 如果不處理第二個參數,我不會出錯。

UPD2。 我的代碼表現得很奇怪。 我認為這可能是混合extern "C"和C ++代碼的問題。

UPD3。 原來這是堆損壞。 我不明白原因在哪里。 可能這與lua根本無關。

最后! 將Lua代碼重新編譯為C ++代碼不起作用(肯定的事情是,我不必再擔心extern "C" )。 但是我發現了兩個多余的lua_pop()調用。 我刪除了它們,現在工作正常。

我沒想到Lua會如此危險!

暫無
暫無

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

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