Search code examples
clua

How to push a table onto the Lua stack


Please explain, I need to put an analogue of this table on the Lua stack in C:

table_ = 
{
    param_1 = "Y1234",
    param_2 = "XXX",
    param_3 = "M"
}

I found the "lua_createtable" function:

https://www.lua.org/manual/5.3... a_newtable

void lua_createtable (lua_State *L, int narr, int nrec);

Creates a new empty table and pushes it onto the stack. Parameter narr is a hint for how many elements the table will have as a sequence; parameter nrec is a hint for how many OTHER elements the table will have. Lua may use these hints to preallocate memory for the new table. This preallocation is useful for performance when you know in advance how many elements the table will have. Otherwise you can use the function lua_newtable.

I can’t understand - the parameters narr and nrec.

narr - how many elements will be in the table as a sequence. What is "as a sequence"? What's the sequence?

nrec - is a hint about how many OTHER elements will be in the table. What does others mean? What others ?

And it is not clear, after I create an empty table and it is marked on the stack, how can I fill this table with "key - value" values?


Solution

  • From same manual:

    A table with exactly one border is called a sequence. For instance, the table {10, 20, 30, 40, 50} is a sequence, as it has only one border (5). The table {10, 20, 30, nil, 50} has two borders (3 and 5), and therefore it is not a sequence. The table {nil, 20, 30, nil, nil, 60, nil} has three borders (0, 3, and 6), so it is not a sequence, too. The table {} is a sequence with border 0. Note that non-natural keys do not interfere with whether a table is a sequence.

    As for filling that table, you use lua_setfield, so you can do something like this:

    lua_createtable(L, 0, 2);
    
    lua_pushinteger(L, some_number_value);
    lua_setfield(L, -2, "field_1");
    
    lua_pushstring(L, some_string_value);
    lua_setfield(L, -2, "field_2");