clualua-tableluac

Accessing Lua subtables fields from C


I want to store model description in Lua and read it non-sequental. All data is store in incremental order

device_pins = 
{
    {is_digital=true, name = "A", number = 1, on_time=15000000000, off_time=22000000000},
    {is_digital=true, name = "B", number = 2, on_time=15000000000, off_time=22000000000},
    {is_digital=true, name = "C", number = 3, on_time=15000000000, off_time=22000000000}    
}

It is mostly the same way I store that data in C struct. So I want to loop through device_pins, like device_pins[1..3] and access subtable values, like I do it in Lua: device_pins[1].name etc. So far I can iterate through tables but can't access subtables fields, I tried lua_getfield but seems it is not suitable here

lua_getglobal (luactx, "device_pins");
if (0 == lua_istable(luactx, 1))
{
    out_log("No table found");
}
lua_pushnil(luactx);
while (lua_next(luactx, 1) != 0) 
{    
out_log(lua_typename(luactx, lua_type(luactx, -1)));   
lua_pop(luactx, 1);
}

Solution

  • Try this instead:

    lua_getglobal (luactx, "device_pins");
    if (0 == lua_istable(luactx, -1))
    {
        out_log("No table found");
    }
    for (i=1; ; i++)
    {    
        lua_rawgeti(luactx,-1,i);
        if (lua_isnil(luactx,-1)) break;
        out_log(luaL_typename(luactx, -1));   
        lua_getfield(luactx,-1,"name");
        out_log(lua_tostring(luactx,-1));   
        lua_pop(luactx, 2);
    }
    

    It is easier to keep track of the stack contents if you use relative (=negative) stack positions.