【发布时间】:2021-02-25 03:57:27
【问题描述】:
我有一个关于lua和c语言绑定的问题。
lua 使用示例)
a[1].b.c[1].d = 1
a[1].b.c[2].d = 2
a[2].b.c[1].d = 3
a[2].b.c[2].d = 4
我想知道如何使用 lua C api 创建它。 这是我在 C 中使用的代码
lua_createtable(L, 2, 0);
lua_pushnumber(L, 1);
{
lua_createtable(L, 0, 1);
{
lua_newtable(L);
lua_pushnumber(L, 1);
{
lua_pushnumber(L, 49);
lua_setfield(L, -2, "d");
lua_settable(L, -3);
}
lua_pushnumber(L, 2);
{
lua_pushstring(L, "old");
lua_setfield(L, -2, "d");
lua_settable(L, -3);
}
lua_setfield(L, -2, "c");
}
lua_setfield(L, -2, "b");
}
lua_pushnumber(L, 2);
{
lua_createtable(L, 0, 1);
{
lua_newtable(L);
lua_pushnumber(L, 1);
{
lua_pushnumber(L, 49);
lua_setfield(L, -2, "d");
lua_settable(L, -3);
}
lua_pushnumber(L, 2);
{
lua_pushstring(L, "old");
lua_setfield(L, -2, "d");
lua_settable(L, -3);
}
lua_setfield(L, -2, "c");
}
lua_setfield(L, -2, "b");
}
lua_setglobal(L, "a");
顺便说一句 PANIC:调用 Lua API 时出现不受保护的错误(尝试索引数字值) 我遇到了这样的错误
非常感谢你告诉我这些。
【问题讨论】:
-
你为什么在每个
lua_newtable之后都做lua_pushnumber?另外,你为什么要这样组合lua_setfield和lua_settable?也许你可以在你的代码中添加一些 cmets 来澄清,否则它很难阅读。