Reputation: 51
I have a problem iterating a multidimensional Lua table in C.
Let the Lua table be this i.e.:
local MyLuaTable = {
{0x04, 0x0001, 0x0001, 0x84, 0x000000},
{0x04, 0x0001, 0x0001, 0x84, 0x000010}
}
I tried to extend the C sample code:
/* table is in the stack at index 't' */
lua_pushnil(L); /* first key */
while (lua_next(L, t) != 0) {
/* uses 'key' (at index -2) and 'value' (at index -1) */
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}
by the second dimension:
/* table is in the stack at index 't' */
lua_pushnil(L); /* first key */ /* Iterating the first dimension */
while (lua_next(L, t) != 0)
{
/* uses 'key' (at index -2) and 'value' (at index -1) */
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
if(lua_istable(L, -1))
{
lua_pushnil(L); /* first key */ /* Iterating the second dimension */
while (lua_next(L, -2) != 0) /* table is in the stack at index -2 */
{
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
}
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}
The output is:
"number - table" (from the first dimension)
"number - number" (from the second dimension)
"number - thread" (from the second dimension)
Afterwards my code crashes in the "while (lua_next(L, -2) != 0)"
Has anybody an idea how to correctly iterate the two dimensional Lua table?
Upvotes: 4
Views: 690
Reputation: 18410
The lua_pop(L, 1)
from the second dimension is outside your iteration!
while (lua_next(L, -2) != 0) /* table is in the stack at index -2 */
{
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
}
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
You need to put it inside the while-loop to get it working to have the value removed, which lua_next()
in your while-condition implicitly puts on the stack.
while (lua_next(L, -2) != 0) /* table is in the stack at index -2 */
{
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}
This way it should work as expected.
Upvotes: 4