如何使用 C API 创建嵌套的 Lua 表 [英] How to create nested Lua tables using the C API

查看:40
本文介绍了如何使用 C API 创建嵌套的 Lua 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个表格

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.

这篇关于如何使用 C API 创建嵌套的 Lua 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆