1

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

3
  • How does it not work precisely? You are probably attempting to set an array item with lua_setfield. Use lua_seti instead. Commented Mar 8, 2022 at 10:42
  • @NickZavaritsky see my update Commented Mar 8, 2022 at 10:51
  • but lua_rawseti exists and that worked fine. Thanks! Commented Mar 8, 2022 at 11:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.