Access Lua subtitle fields from C

I want to save the model description in Lua and consider it non-sequential. All data is stored incrementally.

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}    
}

I mainly store this data in a C struct. So I want to iterate over device_pins, for example device_pins [1..3], and get the values ​​of the subtable, for example, I do it in Lua: device_pins [1] .name, etc. While I can iterate through the tables, but cannot access the sub-fields, I tried lua_getfield, but it seems that it doesn’t work 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);
}
+4
source share
1 answer

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's easier to keep track of the contents of the stack if you use relative (= negative) stack positions.

+2
source

All Articles