【问题标题】:How to create Lua table from C structure如何从 C 结构创建 Lua 表
【发布时间】:2021-10-05 22:58:18
【问题描述】:

我正在尝试从 C 创建一个 Lua 表。我遇到了一个问题: 我正在尝试使用 C 创建一个 Lua 表。 表格应该是这样的:

CharList = {
    [1] = {name = "Kyra", is_monster = false}
    [2] = {name = "Saya", is_monster = false}
    [3] = {name = "Imp", is_monster = true}
}

但是这样做的例子多种多样,我似乎无法让它发挥作用。 我最后一次失败的尝试:

lua_createtable(L, cl->num_chars, 2);
for(i=0;i<cl->num_chars;i++)
{
        character_t *c = &cl->list[i];

        lua_pushstring(L, c->name);
        lua_setfield(L, -2, "name");

        lua_pushboolean(L, c->is_monster);
        lua_setfield(L, -2, "is_monster");

        lua_settable(L, -3);
}
lua_setglobal(L, "charList"); 

【问题讨论】:

    标签: lua lua-api


    【解决方案1】:

    您需要创建子表:

    character_t *c = &cl->list[i];
    lua_pushinteger(L, i+1);
    lua_createtable(L, 0, 2);
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      相关资源
      最近更新 更多