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