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

2021-12-30 00:00:00 lua c++ lua-table lua-api

我想创建一个表格

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);

在循环中创建内部表.之前,这个循环,我用

to create the inner tables in a loop. Before, this loop, I use

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

为 2 个数字槽创建外部表.

to create the outer table for 2 numeric slots.

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

But how can I save the inner tables to the outer table?

推荐答案

这是一个完整的最小程序,演示了如何嵌套表.基本上你缺少的是 lua_setfield 函数.>

Here's a full and minimal program demonstrating how to nest tables. Basically what you are missing is the lua_setfield function.

#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
", lua_tostring(L, -1));
    }

    return 0;
}

程序将简单地打印true.

如果你需要数字索引,那么你继续使用lua_settable:

If you need numeric indices, then you continue using 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
", lua_tostring(L, -1));
    }

    return 0;
}

您可能想使用 lua_objlen,而不是像我那样使用 0 的绝对索引 生成索引.

Rather than using absolute indices of 0 like I did, you might want to use lua_objlen to generate the index.

相关文章