使用 Lua 表 C API 创建一个简单的表
我正在运行一个总是返回 4 行的 MySQL 查询:
I'm running a MySQL query which always returns 4 rows:
row->name
、row->date
、row->ip
、row->custom
我想要实现的是基于上述结果创建一个简单的表格,它看起来像:
What I want to achieve is create a simple table basing on the above results so it would look like:
{
"name" = result of row->name,
"date" = result of row->date,
"ip" = result of row->ip,
"custom" = result of row->custom
}
我尝试了多种可能性,但发布的示例确实多种多样,而且我在使其工作时遇到了问题.
I have tried multiple possibilities, but the examples posted are really varied and I got a problems making it working.
我最后一次失败的尝试:
My last unsuccessful try:
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
.如果您需要更多,必须重复.
As I mentioned in comment, lua_settable()
takes care only of one key, value
pair. Must repeat that if You need more.
我更喜欢像这样保存 Lua 堆栈空间:
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. */
此外,您可以编写某种 C 结构迭代器或其他东西.
Also, You could write some kind of C struct iterator or something.
注意:如果这是用于某种 Lua 包装器 - 您应该确保 标准化这样做的方式.在以下示例中,应用了 @lhf 注释,将其缩短一点:
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;
}
修复了 lua_setfield()
的使用@lhf 注意.谢谢!
Fixes usage of lua_setfield()
by @lhf note. Thanks!