在 C 中迭代多维 Lua 表

2024-01-08

我在 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 表吗?


The lua_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 循环中才能使其正常工作以删除该值,这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);
  }

这样它应该按预期工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C 中迭代多维 Lua 表 的相关文章

随机推荐