在C中迭代多维Lua表

在C中迭代多维Lua表,c,loops,multidimensional-array,lua,lua-table,C,Loops,Multidimensional Array,Lua,Lua Table,我在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) !

我在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 */ /* 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);
}
输出为:

数字-表格””(从第一个维度开始)

数字-数字”(从第二维度)

编号-螺纹””(从第二维度)

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

有人知道如何正确迭代二维Lua表吗?

第二维的Lua\u pop(L,1)超出了您的迭代范围

  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);
您需要将其放入while循环中,以使其工作,从而删除该值,while条件中的
lua_next()
会隐式地将该值放入堆栈中

  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);
  }
这样,它应该像预期的那样工作