在C中迭代多维Lua表

我在C语言中遇到了一个多维Lua表迭代的问题。

让Lua表像这样:

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

我试图扩展C示例代码:

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

通过第二个维度:

/* 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)));

   if(lua_istable(L, -1))
   {
      lua_pushnil(L);  /* first key */ /* 迭代第二维 */
      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);
}

输出为:

" number - table" (来自第一维)

" number - number" (来自第二维)

" number - thread" (来自第二维)

之后我的代码在"while (lua_next(L, -2) != 0)"处崩溃

有没有人知道如何正确迭代两维Lua表?

点赞
用户5636775
用户5636775

你需要把 lua_pop(L, 1) 放在 while 循环内部,以使其正常工作并且将该值移除,这是因为 lua_next() 在 while 条件中隐式地将其放在堆栈上。

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

这样它应该按预期工作。

2017-07-05 08:49:02