c - 如何使用c代码读取复杂的lua表

标签 c lua

我开始进入 lua 世界,目前我正在使用 C 代码创建表格读数

我有一个看起来像这样的表:

Consume = 
{
    Consume_first = {
        Value = 100
        Request = 200
    },
    Require_var = {
        Enable= true
        Name = "Am"
    
    }
}

我想知道一些信息

Consume 定义为 lua_getglobal(L, "Consume");

ValueRequestEnableNamelua_getfield 函数用过吗?

例子:

lua_getfield(L, 1, "Value")

Consume_firstRequire_var 中我应该用什么来定义它们?

我的代码:

void read_table(void) {
    lua_State *L;
    L = luaL_newstate();
    luaL_openlibs(L);

    if (luaL_loadfile(L, "table.lua") || lua_pcall(L, 0, 0, 0))
    {
        ShowError("Error reading 'table.lua'\n");
        return;
    }

    lua_getglobal(L, "Consume");
    .... 
    lua_getfield(L, -1, "Value");
    lua_getfield(L, -1, "Request");
    ....
    lua_getfield(L, -1, "Enable");
    lua_getfield(L, -1, "Name");

    lua_close(L);
    printf("Read Table complete.\n");

}

我正在使用 lua 5.4

最佳答案

像这样:

lua_getglobal(L, "Consume");

// Get Consume.Consume_first
lua_getfield(L, -1, "Consume_first");

// Get Consume.Consume_first.Value
lua_getfield(L, -1, "Value");

// Get Consume.Consume_first.Request
// Note that currently Consume.Consume_first.Value is on the stack
// So Consume.Consume_first is at index -2
lua_getfield(L, -2, "Request");

如果你对索引感到困惑,也可以使用lua_gettop来帮忙。

lua_getglobal(L, "Consume");

// Get Consume.Consume_first
lua_getfield(L, -1, "Consume_first");
int Consume_first_index = lua_gettop(L);

// Get Consume.Consume_first.Value
lua_getfield(L, Consume_first_index, "Value");

// Get Consume.Consume_first.Request
lua_getfield(L, Consume_first_index, "Request");

关于c - 如何使用c代码读取复杂的lua表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74527605/

相关文章:

c - 有没有办法用位字段声明无符号固定宽度整数?

c - 无法发现内存泄漏 cStringUsingEncoding

c - 在 MinGW 32 位上确定 C 中的 64 位文件大小

Lua:用括号括起来时类变量的 bool 转换的解决方法

lua - 你可以在 lua 表的键中使用冒号吗

Lua:循环中的 string.gsub 模式滞后

c - 当仍有大量交换空间时,malloc 失败

c - 在 c 中使用信号

C++类和lua

c - 将大型二进制数据从 Lua 传递到 C 的最佳方法