lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


That won't work either because the index is relative and there will be
more stuff on the stack.

This may or may not work (untested) but should be close:

void itr_table(lua_State* L, int idx)
{
  lua_pushnil(L);
  while (lua_next(L, idx))
  {
     if (lua_type(L, -1) == LUA_TTABLE)
        itr_table(L, lua_gettop(L));

     lua_pop(L, 1);
  }
}


Then to do the global table:

itr_table(L, LUA_GLOBALSINDEX);

CR


On 1/19/07, Jérôme VUARAND <jerome.vuarand@gmail.com> wrote:
2007/1/19, Raymond Jacobs <raymondj@gmail.com>:
> int idx=LUA_GLOBALSINDEX;
> lua_getfenv(l,idx);
>
> while(lua_next(l,idx)!=0)
> {
>                 const char* key=lua_tostring(l,-2);
>
>                 //get value at -1 index and check type of it
>
>                 //do somthing with key and value based on type of value
>                 //if value is a table call this function again to traverse it, then
> continue here
>
>
>                 lua_pop(l,1);
> }
>
> it seems in theory it should be as simple as doing another lua_next,
> however I've not been able to get it to work, and I end up crashing,
> likely due to corupting the stack; either my logic or how I'm going
> about it is wrong, an example of how to do this in the C API would be
> really helpful.

You forget to push an initial nil on the stack before entering you
while loop (see lua_next documentation example). Here is what your
code could look like :

int dosomestuff(lua_State* L, int index)
{
    // Do something with value at index (which is not a table)
    return 1;
}

int parsetable(lua_State* L, int index)
{
    // Push an initial nil to init lua_next
    lua_pushnil(L);
    // Parse the table at index
    while (lua_next(index)!=0)
    {
        if (lua_istable(L, -1)
        {
            parsetable(L, -1);
        }
        else
        {
            dosomestuff(L, -1);
        }
        // Pop value, keep key
        lua_pop(L, 1);
    }
    return 1;
}

int parseglobals(lua_State* L)
{
    parsetable(L, LUA_GLOBALSINDEX);
    return 0;
}