我正在运行一个总是返回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
}
我尝试了多种可能性,但发布的示例确实多种多样,我在使其工作时遇到了问题。
我最后一次尝试失败:
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);
答案 0 :(得分: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. */
此外,您可以编写某种C struct迭代器或其他东西。
注意:如果这是针对某种Lua包装器的 - 您应该确保standardized way of doing that。在以下示例中,应用了@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;
}
编辑:通过lua_setfield()
注意修复@lhf的使用情况。谢谢!