gpt4 book ai didi

c++ - 如何使用 C API 创建嵌套的 Lua 表

转载 作者:可可西里 更新时间:2023-11-01 17:01:16 24 4
gpt4 key购买 nike

我想创建一个表

myTable = {
[0] = { ["a"] = 4, ["b"] = 2 },
[1] = { ["a"] = 13, ["b"] = 37 }
}

使用 C API?

我目前的做法是

lua_createtable(L, 0, 2);
int c = lua_gettop(L);
lua_pushstring(L, "a");
lua_pushnumber(L, 4);
lua_settable(L, c);
lua_pushstring(L, "b");
lua_pushnumber(L, 2);
lua_settable(L, c);

循环创建内表。之前,这个循环,我用

lua_createtable(L, 2, 0);
int outertable = lua_gettop(L);

为 2 个数字槽创建外表。

但是如何将内表保存到外表呢?

最佳答案

这是一个完整的最小程序,演示了如何嵌套表格。基本上你缺少的是 lua_setfield功能。

#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

int main()
{
int res;
lua_State *L = lua_open();
luaL_openlibs(L);

lua_newtable(L); /* bottom table */

lua_newtable(L); /* upper table */

lua_pushinteger(L, 4);
lua_setfield(L, -2, "four"); /* T[four] = 4 */
lua_setfield(L, -2, "T"); /* name upper table field T of bottom table */
lua_setglobal(L, "t"); /* set bottom table as global variable t */

res = luaL_dostring(L, "print(t.T.four == 4)");
if(res)
{
printf("Error: %s\n", lua_tostring(L, -1));
}

return 0;
}

程序将简单地打印true

如果您需要数字索引,则继续使用 lua_settable :

#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

int main()
{
int res;
lua_State *L = lua_open();
luaL_openlibs(L);

lua_newtable(L); /* bottom table */

lua_newtable(L); /* upper table */

lua_pushinteger(L, 0);
lua_pushinteger(L, 4);
lua_settable(L, -3); /* uppertable[0] = 4; pops 0 and 4 */
lua_pushinteger(L, 0);
lua_insert(L, -2); /* swap uppertable and 0 */
lua_settable(L, -3); /* bottomtable[0] = uppertable */
lua_setglobal(L, "t"); /* set bottom table as global variable t */

res = luaL_dostring(L, "print(t[0][0] == 4)");
if(res)
{
printf("Error: %s\n", lua_tostring(L, -1));
}

return 0;
}

与其像我一样使用 0 的绝对索引,不如使用 lua_objlen生成索引。

关于c++ - 如何使用 C API 创建嵌套的 Lua 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1630169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com