Creating a simple table with Lua tables C API

后端 未结 1 607
清歌不尽
清歌不尽 2021-02-04 12:37

I\'m running a MySQL query which always returns 4 rows:

row->name, row->date, row->ip, row->custom

<
相关标签:
1条回答
  • 2021-02-04 13:32

    As I mentioned in comment, lua_settable() takes care only of one key, value pair. Must repeat that if You need more.

    I'd prefer saving the Lua stack space like this:

    lua_createtable(L, 0, 4);
    
    lua_pushstring(L, "name");
    lua_pushstring(L, row->name);
    lua_settable(L, -3);  /* 3rd element from the stack top */
    
    lua_pushstring(L, "date");
    lua_pushstring(L, row->date);
    lua_settable(L, -3);
    
    lua_pushstring(L, "ip");
    lua_pushstring(L, row->ip);
    lua_settable(L, -3);
    
    lua_pushstring(L, "custom");
    lua_pushstring(L, row->custom);
    lua_settable(L, -3);
    
    /* We still have table left on top of the Lua stack. */
    

    Also, You could write some kind of C struct iterator or something.

    NOTE: if this is for some kind of Lua wrapper - You should ensure standardized way of doing that. In the following example applied @lhf comment about shortening it a bit:

    int 
    l_row_push(lua_State *l)
    {
        lua_createtable(L, 0, 4); /* creates and pushes new table on top of Lua stack */
    
        lua_pushstring(L, row->name); /* Pushes table value on top of Lua stack */
        lua_setfield(L, -2, "name");  /* table["name"] = row->name. Pops key value */
    
        lua_pushstring(L, row->date);
        lua_setfield(L, -2, "date");
    
        lua_pushstring(L, row->ip);
        lua_setfield(L, -2, "ip");
    
        lua_pushstring(L, row->custom);
        lua_setfield(L, -2, "custom");
    
        /* Returning one table which is already on top of Lua stack. */
        return 1;
    }
    

    EDIT: Fixes usage of lua_setfield() by @lhf note. Thanks!

    0 讨论(0)
提交回复
热议问题