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

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

row->namerow->daterow->iprow->custom

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

 { "name" = result of row->name, "date" = result of row->date, "ip" = result of row->ip, "custom" = result of row->custom } 

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

我最后一次尝试不成功:

 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); 

正如我在评论中提到的, 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. */ 

此外,您可以编写某种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; } 

编辑:通过@lhf note修复lua_setfield()的使用 。 谢谢!