正如我在评论中提到的,lua_settable() http://pgl.yoyo.org/luai/i/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 结构迭代器或其他东西。
注意:如果这是某种 Lua 包装器 - 你应该确保这样做的标准化方法 http://www.lua.org/manual/5.1/manual.html#lua_CFunction。在下面的例子中应用了@lhf https://stackoverflow.com/users/107090/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() http://pgl.yoyo.org/luai/i/lua_setfield by @lhf https://stackoverflow.com/users/107090/lhf笔记。谢谢!