使用Lua表C API创建一个简单的表

Luc*_*cas 8 c api lua

我正在运行一个总是返回4行的MySQL查询:

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

我想要实现的是基于上面的结果创建一个简单的表,所以它看起来像:

{
     "name" = result of row->name,
     "date" = result of row->date,
     "ip"   = result of row->ip,
     "custom" = result of row->custom
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了多种可能性,但发布的示例确实多种多样,我遇到了问题,使其正常工作.

我最后一次尝试不成功:

lua_createtable(L, 0, 4);
top = lua_gettop(L);
lua_pushstring(L, "name");
lua_pushstring(L, row->name);
lua_pushstring(L, "date");
lua_pushnumber(L, row->date);
lua_pushstring(L, "ip");
lua_pushstring(L, row->ip);
lua_pushstring(L, "custom");
lua_pushstring(L, row->custom);
lua_settable(L, top);
Run Code Online (Sandbox Code Playgroud)

Kam*_*olo 11

正如我在评论中提到的那样,lua_settable()只关注一key, value对.必须重复,如果您需要更多.

我更喜欢像这样保存Lua堆栈空间:

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. */
Run Code Online (Sandbox Code Playgroud)

此外,您可以编写某种C struct迭代器或其他东西.

注意:如果这是针对某种Lua包装器 - 您应该确保标准化的方式.在下面的示例中应用@lhf评论有关缩短它:

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:修正的使用lua_setfield()@lhf音符.谢谢!