0
votes

I have a Lua function that returns a dictionary table, and one of the values that's put into the returned table is another table as demonstrated in the following Lua function.

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

How would I go about accessing that inner table?

I know I can get to the table, because I can enter the following if statement. My current attempt at reading the table is included as well.

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

I'm pretty sure there's an easy solution to this, but I'm totally stumped. Any help would be much appreciated.

2
Have you tried running in a debugger? Also, how is lua declared and initialized in your C++ code? - smocking
Here is a bit of checking types on the stack lua-users.org/lists/lua-l/2002-11/msg00104.html and here is an example that talks about stack pop gamedev.net/topic/332365-lua-get-table-content finally check this stackoverflow.com/questions/3970021/… - Richard Chambers
And actually this article, forum.gpwiki.org/viewtopic.php?t=9106 seems to be exactly what you want. - Richard Chambers
smocking - yes, still just crashes to desktop. lua is the active lua_State created by lua_open(). - Dar13
There is no way you enter that if statement. You push a string, and then ask if the string is a table. That will never be true. So odds are good that this isn't your actual code, or you're getting other problems. - Nicol Bolas

2 Answers

3
votes

After you push the index, the table is one more slot away in the stack. So something like this should work:

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

It is generally easier to use functions lua_getfield (for string indexes) or lua_rawgeti (for numerical indexes) than the raw lua_gettable function.

In particular, that avoids the extra value on the stack that causes your indexing error.

The example could be rewritten as :

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