带有关键字的子表

早上好 我需要将C语言的返回结构转换为Lua。 我的结构拥有命名字段,其中一个是其他命名结构的数组:

{
    "foo": 1,
    "bar": [
        {"field1": 11, "field2": 12},
        {"field1": 21, "field2": 22}
    ],
    "baz": 3
}

我编写了这段代码:

lua_createtable(L, 0, 3); //0的索引项,3的键控项

lua_pushnumber(L, 1);
lua_setfield(L, -2, "foo"); //root.foo = 1;

lua_createtable(L, 2, 0); //带有2个索引项和0个键值项的子表

lua_pushnumber(L, 1); //设置当前项目索引为1

lua_createtable(L, 0, 2); //带有2个键值项的子表

lua_pushnumber(L, 11);
lua_setfield(L, -2, "field1"); //root.bar[0].field1 = 11;

lua_pushnumber(L, 12);
lua_setfield(L, -2, "field2"); //root.bar[0].field2 = 12;

lua_settable(L, -2); //设置root.bar [0]

lua_pushnumber(L, -2); //设置当前项目索引为2

lua_createtable(L, 0, 2); //第二项带有2个键的表

lua_pushnumber(L, 21);
lua_setfield(L, -2, "field1"); //root.bar[1].field1 = 21;

lua_pushnumber(L, 22);
lua_setfield(L, -2, "field2"); //root.bar[1].field2 = 22;

lua_settable(L, -2); //设置root.bar[1]
lua_setfield(L, -2, "bar"); //设置root.bar

lua_pushnumber(L, 3);
lua_setfield(L, -2, "baz"); //root.baz = 3;

但是它抛出异常。之前我尝试使用lua_setfield(L, -2, "bar")为子表设置后,没有使用lua_settable方法检测到的结构如下:

root.field1 = 21
root.field2 = 22
root.baz = 3

我应该如何实现目标结构?

点赞