lualua-api

How to create Lua table from C structure


I'm trying to create a Lua table from C. I've got a problem: I'm trying to create a Lua table using C. The table should be like this:

CharList = {
    [1] = {name = "Kyra", is_monster = false}
    [2] = {name = "Saya", is_monster = false}
    [3] = {name = "Imp", is_monster = true}
}

But the examples to do this are varied and I can't seem to get it to work. My last unsuccessful try:

lua_createtable(L, cl->num_chars, 2);
for(i=0;i<cl->num_chars;i++)
{
        character_t *c = &cl->list[i];

        lua_pushstring(L, c->name);
        lua_setfield(L, -2, "name");

        lua_pushboolean(L, c->is_monster);
        lua_setfield(L, -2, "is_monster");

        lua_settable(L, -3);
}
lua_setglobal(L, "charList"); 

Solution

  • You need to create the subtables:

    character_t *c = &cl->list[i];
    lua_pushinteger(L, i+1);
    lua_createtable(L, 0, 2);
    ...