我开始进入 lua 世界,目前我正在使用 C 代码创建表格读数
我有一个看起来像这样的表:
Consume =
{
Consume_first = {
Value = 100
Request = 200
},
Require_var = {
Enable= true
Name = "Am"
}
}
我想知道一些信息
Consume 定义为 lua_getglobal(L, "Consume")
;
Value、Request、Enable 和 Name 是 lua_getfield
函数用过吗?
例子:
lua_getfield(L, 1, "Value")
在 Consume_first 和 Require_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/