lua c read nested tables

那年仲夏 提交于 2019-12-05 09:47:01

You are not too far. The key here is to understand how the Lua API use the stack for everything.

Here is an untested code sample which should get you going:

// this will be used to validate our table
static struct {
    const char * name;
    int type;
} fields[] = {
    {"port", LUA_TNUMBER},
    {"address", LUA_TSTRING},
    {"userdata", LUA_TSTRING},
    NULL
};

lua_getglobal(L, "listen");

// the 'listen' table should be at the top of the stack
luaL_checktype(L, -1, LUA_TTABLE);

// iterate the listen table
int i;
for (i = 1; ; i++) {
    lua_rawgeti(L, -1, i);
    // when you get nil, you're done
    if (lua_isnil(L, -1)) {
        lua_pop(L,1);
        break;
    }
    // an element of the 'listen' table should now be at the top of the stack
    luaL_checktype(L, -1, LUA_TTABLE);
    // read the content of that element
    int field_index;
    for (field_index = 0; fields[field_index] != NULL; field_index++) {
        lua_getfield(L, -1, fields[field_index].name);
        luaL_checktype(L, -1, fields[field_index].type);
        // you should probably use a function pointer in the fields table.
        // I am using a simple switch/case here
        switch(field_index) {
        case 0:
            port = lua_tonumber(L, -1);
            // do what you want with port
            break;
        case 1:
            address = lua_tostring(L, -1);
            break;
        case 2:
            // handle userdata
            break;
        }
        // remove the field value from the top of the stack
        lua_pop(L, 1); 
    }
    // remove the element of the 'listen' table from the top of the stack.
    lua_pop(L, 1);
}

I suggest you use those documentations: Lua API table Lua API ref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!