2012-08-15 134 views
0

我有一個Lua函數返回一個字典表,其中一個放入返回表的值是另一個表,如下面的Lua函數所演示的。從C++中訪問表中的Lua表

function tableWithinTable() 
    local ret = {} 
    ret["a"] = 1 
    ret["b"] = {1,2,3} 
    ret["c"] = 3 
    return ret 
end 

我該如何去訪問內表?

我知道我可以到表中,因爲我可以輸入以下if語句。我目前的閱讀表的嘗試也包括在內。

lua_pushstring("b"); 
lua_gettable(lua,1); 
if(lua_istable(lua,-1)) 
{ 
    //whatever is in here is executed. 
    lua_pushnumber(lua,1); 
    lua_gettable(lua,-1); //crashes to desktop here 
    std::cout << lua_tonumber(lua,-1) << std::endl; 
    lua_pop(lua,1); 
} 

我很確定有一個簡單的解決方案,但我完全難住。任何幫助將非常感激。

+0

您是否嘗試過在調試器中運行?另外,如何在您的C++代碼中聲明並初始化'lua'? – smocking 2012-08-15 18:50:41

+0

這裏有一些檢查類型堆棧http://lua-users.org/lists/lua-l/2002-11/msg00104.html這裏是一個例子,談論堆棧彈出http:// www。 gamedev.net/topic/332365-lua-get-table-content/終於檢查這個http://stackoverflow.com/questions/3970021/how-to-read-lua-table-return-value-from-c – 2012-08-15 18:57:11

+1

而且實際上這篇文章,http://forum.gpwiki.org/viewtopic.php?t=9106似乎正是你想要的。 – 2012-08-15 19:00:03

回答

3

按下索引後,表格在堆棧中距離多一個槽。所以,這樣的事情應該工作:

if(lua_istable(lua,-1)) { 
    lua_pushnumber(lua,1); 
    lua_gettable(lua,-2); 
    ... 
0

這是通常更易於使用的功能lua_getfield(字符串索引)或lua_rawgeti(用於數字索引)比原始lua_gettable功能。

特別是,它避免了導致索引錯誤的堆棧上的額外值。

的例子可以寫成:

lua_getfield(lua, 1, "b"); 
if(lua_istable(lua, -1)) 
{ 
    lua_rawgeti(lua, -1, 1); 
    std::cout << lua_tonumber(lua,-1) << std::endl; 
    lua_pop(lua, 1); 
}