[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: recursively traverse globals table from C API
- From: "Jérôme VUARAND" <jerome.vuarand@...>
- Date: Fri, 19 Jan 2007 21:31:06 -0500
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;
}