如何使用 Lua C API 创建多维数组

我想咨询一下 Lua 和 C 语言之间的绑定问题。

lua 使用示例)

a[1].b.c[1].d = 1
a[1].b.c[2].d = 2
a[2].b.c[1].d = 3
a[2].b.c[2].d = 4

我想知道如何使用 Lua C API 创建这个数组。 这是我在 C 中编写的代码

    lua_createtable(L, 2, 0);
lua_pushnumber(L, 1);
{
    lua_createtable(L, 0, 1);
    {
        lua_newtable(L);
        lua_pushnumber(L, 1);
        {
            lua_pushnumber(L, 49);
            lua_setfield(L, -2, "d");
            lua_settable(L, -3);
        }
        lua_pushnumber(L, 2);
        {
            lua_pushstring(L, "old");
            lua_setfield(L, -2, "d");
            lua_settable(L, -3);
        }
        lua_setfield(L, -2, "c");
    }
    lua_setfield(L, -2, "b");
}
lua_pushnumber(L, 2);
{
    lua_createtable(L, 0, 1);
    {
        lua_newtable(L);
        lua_pushnumber(L, 1);
        {
            lua_pushnumber(L, 49);
            lua_setfield(L, -2, "d");
            lua_settable(L, -3);
        }
        lua_pushnumber(L, 2);
        {
            lua_pushstring(L, "old");
            lua_setfield(L, -2, "d");
            lua_settable(L, -3);
        }
        lua_setfield(L, -2, "c");
    }
    lua_setfield(L, -2, "b");
}
lua_setglobal(L, "a");

顺便说一下 PANIC: unprotected error in call to Lua API (attempt to index a number value) 我得到了这样的错误

非常感谢您告诉我。

点赞
用户4984564
用户4984564
lua_createtable(L, 2, 0); // 栈顶:{}
lua_pushnumber(L, 1); // 栈顶:{}, 1
{
    lua_createtable(L, 0, 1); // 栈顶:{}, 1, {}
    {
        lua_newtable(L); // 栈顶:{}, 1, {}, {}
        lua_pushnumber(L, 1); // 栈顶:{}, 1, {}, {}, 1
        {
            lua_pushnumber(L, 49); // 栈顶:{}, 1, {}, {}, 1, 49
            lua_setfield(L, -2, "d"); // !!!!!!!
            // 栈顶有两个数字,索引 -2 指向数字 1,尝试在该索引上执行 lua_setfield 操作失败,
            // 因为该操作需要的是一个表格,但在该索引上找到的是一个整数。
            lua_settable(L, -3);
            // ...
        }
        // ...
    }
    // ...
}
2020-11-13 07:59:08