从C中获取Lua子表字段

我想要在 Lua 中存储模型描述,并且以非顺序的方式读取它。所有的数据都按增量顺序存储。

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

这与我在 C 结构中存储这些数据的方式大致相同。我想要循环访问 device_pins,比如像 device_pins[1..3],并且访问子表的值,就像我在 Lua 中所做的那样:device_pins[1].name 等等。到目前为止,我可以遍历表,但无法访问子表字段,我尝试了 lua_getfield,但似乎不适用于这里。

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);
}
点赞
用户107090
用户107090

尝试使用以下代码代替:

lua_getglobal(luactx, "device_pins");
if (0 == lua_istable(luactx, -1))
{
    out_log("没有找到表格");
}
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);
}

如果使用相对(负)堆栈位置,则更容易跟踪堆栈内容。

2014-09-16 23:58:57