Iterating a multidimensional Lua table in C

I have a problem iterating over a multidimensional Lua table in C.

Let the Lua table be ie:

local MyLuaTable = {
  {0x04, 0x0001, 0x0001, 0x84, 0x000000},
  {0x04, 0x0001, 0x0001, 0x84, 0x000010}
}

      

I tried to extend the sample C 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);
 }

      

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

      

Output:

" number - table " (from the first dimension)

" number - number " (from the second dimension)

" number - thread " (from the second dimension)

Subsequently my code crashes into "while (lua_next (L, -2)! = 0)"

Does anyone have an idea how to iterate over a two dimensional Lua table correctly?

+3


source to share


1 answer


lua_pop(L, 1)

from the second dimension is outside of 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 a while loop to make it work to remove the value that is lua_next()

implicitly pushed onto the stack in your while state.



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

      

Thus, it should work as expected.

+3


source







All Articles