{
"foo": 1,
"bar": [
{"field1": 11, "field2": 12},
{"field1": 21, "field2": 22}
],
"baz": 3
}
我写了这段代码:
lua_createtable(L, 0, 3); //0 indexed items, 3 keyed items
lua_pushnumber(L, 1);
lua_setfield(L, -2, "foo"); //root.foo = 1;
lua_createtable(L, 2, 0); //child table for bar field with 2 indexed items and 0 keyed
lua_pushnumber(L, 1); // set current item index to 1
lua_createtable(L, 0, 2); // child table with 2 keyed items
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); //set root.bar[0]
lua_pushnumber(L, -2); //set current item index to 2
lua_createtable(L, 0, 2); //table for second bar items with 2 keys
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); //set root.bar[1]
lua_setfield(L, -2, "bar"); //set root.bar
lua_pushnumber(L, 3);
lua_setfield(L, -2, "baz"); //root.baz = 3;
但它失败了例外。我尝试在没有lua_settable的情况下执行此操作,并在lua_createtalbe(L,2,0)之后为子表调用lua_setfield(L,-2,“bar”),但之后我会收到包含以下字段的结构:
root.field1 = 21
root.field2 = 22
root.baz = 3
我如何实现目标结构?