简体   繁体   中英

Iterating a multidimensional Lua Table in C

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

Let the Lua table be this ie:

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM