Search code examples
lualua-tablelua-c++-connection

Lua table created in C returns strange values for integers


I want to create a nested table, that shall look like this:

{
  SA_1: {1,2,3,4},
  SA_2: {11,22,33,44}
}

The code I have (I changed the SA_2 to strings for testing purposes):

int myRegisteredCfunc:
{
    lua_createtable(L, 0, 2);

    // Create the first inner table
    lua_createtable(L, 0, 4);
    for (int i = 1; i < 5; ++i) {
        lua_pushinteger(L, i);  // Push the corresponding value
        lua_rawseti(L, -2, i);  // Set the value at the index
    }
    // Set the first inner table as a field of the outer table
    lua_setfield(L, -2, "SA_1");

    // Create the second inner table
    char test_str[20];
    lua_createtable(L, 0, 4);
    for (int i = 1; i < 5; ++i) {
        sprintf(test_str, "str %d",i);
        lua_pushstring(L, test_str);  // Push the corresponding value
        lua_rawseti(L, -2, i);  // Set the value at the index
    }
    // Set the second inner table as a field of the outer table
    lua_setfield(L, -2, "SA2_2");

    return 1
}

However, the output I get is:

SA_1 (table):
  4: 3
  1: 4
  2: 3
  3: 3
SA_2 (table):
  4: str 4
  1: str 1
  2: str 2
  3: str 3

The values for SA_1 are not set correctly. I do get 3 times number 3, instead of 1-4. The strange part is, the strings are actually printed correctly.

This is my print function:

    local table = LIB.myRegisteredCfunc() 

    local function print_table(tbl, indent)  
        indent = indent or 0  
        local spaces = string.rep("  ", indent)  
        for k, v in pairs(tbl) do  
            if type(v) == "table" then  
                print(spaces .. k .. " (table):")  
                print_table(v, indent + 1)  
            else  
                print(spaces .. k .. ": " .. tostring(v))  
            end  
        end  
    end 

    print_table(table) 

Solution

    1. Lua is able to create sequence tables, but you passed the wrong parameter, the 2nd parameter is the hint of sequence capacity, so it should be:

      lua_createtable(L, 4, 0);
      
    2. When you use pairs to iterate over a table, its order is always unspecified.