Reputation: 24321
I'm trying to create this datastructure from C:
local table = {
id = 12,
items = {
{
id = 1,
name = "foo",
},{
id = 2,
name = "bar",
}
}
}
However I don't manage to get the anonymous tables working. (It's an array I want but array and tables is the same in lua afaik).
lua_newtable(L);
lua_pushinteger(L, 1);
lua_setfield(L, -2, "id");
lua_newtable(L);
lua_newtable(L);
lua_pushinteger(L, 1);
lua_setfield(L, -2, "id");
lua_pushstring(L, "foo");
lua_setfield(L, -2, "name");
lua_setfield(L, -2, "1");
lua_newtable(L);
lua_pushinteger(L, 1);
lua_setfield(L, -2, "id");
lua_pushstring(L, "bar");
lua_setfield(L, -2, "name");
lua_setfield(L, -2, "2");
lua_setfield(L, -2, "items");
And this gives
{
id = 1,
items = {
["1"] = {
id = 1,
name = "foo"
},
["2"] = {
id = 1,
name = "bar"
}
}
}
I'm using lua 5.1 so I don't have access to lua_seti
Upvotes: 1
Views: 507
Reputation: 1489
As previously mentioned, a table and an array is the same data structure in Lua. In order to “set an array item” it is paramount to use a number as a key. One can’t set an array item with lua_setfield
as it uses string keys. From the output we can see that the function worked exactly as advertised - items were inserted into the table under string keys “1” and “2”.
Please use lua_settable
.
void lua_settable (lua_State *L, int index);
Does the equivalent to t[k] = v, where t is the value at the given valid index, v is the value at the top of the stack, and k is the value just below the top.
Use lua_pushnumber
to push the desired index into the stack, to be used as the key by lua_settable
.
Upvotes: 2