【问题标题】:how to create multidimensionnal array in lua with lau C api如何使用 lua C api 在 lua 中创建多维数组
【发布时间】:2021-02-25 03:57:27
【问题描述】:

我有一个关于lua和c语言绑定的问题。

lua 使用示例)

a[1].b.c[1].d = 1
a[1].b.c[2].d = 2
a[2].b.c[1].d = 3
a[2].b.c[2].d = 4

我想知道如何使用 lua C api 创建它。 这是我在 C 中使用的代码

    lua_createtable(L, 2, 0);
lua_pushnumber(L, 1);
{
    lua_createtable(L, 0, 1);
    {
        lua_newtable(L);
        lua_pushnumber(L, 1);
        {
            lua_pushnumber(L, 49);
            lua_setfield(L, -2, "d");
            lua_settable(L, -3);
        }
        lua_pushnumber(L, 2);
        {
            lua_pushstring(L, "old");
            lua_setfield(L, -2, "d");
            lua_settable(L, -3);
        }
        lua_setfield(L, -2, "c");
    }
    lua_setfield(L, -2, "b");
}
lua_pushnumber(L, 2);
{
    lua_createtable(L, 0, 1);
    {
        lua_newtable(L);
        lua_pushnumber(L, 1);
        {
            lua_pushnumber(L, 49);
            lua_setfield(L, -2, "d");
            lua_settable(L, -3);
        }
        lua_pushnumber(L, 2);
        {
            lua_pushstring(L, "old");
            lua_setfield(L, -2, "d");
            lua_settable(L, -3);
        }
        lua_setfield(L, -2, "c");
    }
    lua_setfield(L, -2, "b");
}
lua_setglobal(L, "a");

顺便说一句 PANIC:调用 Lua API 时出现不受保护的错误(尝试索引数字值) 我遇到了这样的错误

非常感谢你告诉我这些。

【问题讨论】:

  • 你为什么在每个lua_newtable之后都做lua_pushnumber?另外,你为什么要这样组合lua_setfieldlua_settable?也许你可以在你的代码中添加一些 cmets 来澄清,否则它很难阅读。

标签: lua lua-api


【解决方案1】:
lua_createtable(L, 2, 0); // Stack: {}
lua_pushnumber(L, 1); // Stack: {}, 1
{
    lua_createtable(L, 0, 1); // Stack: {}, 1, {}
    {
        lua_newtable(L); // Stack: {}, 1, {}, {}
        lua_pushnumber(L, 1); // Stack: {}, 1, {}, {}, 1
        {
            lua_pushnumber(L, 49); // Stack: {}, 1, {}, {}, 1, 49
            lua_setfield(L, -2, "d"); // !!!!!!!
            // You currently have two numbers at the top of the stack.
            // the index -2 thus points to the number 1
            // Trying to lua_setfield on that index fails because it expects
            // a table but finds an integer instead.
            lua_settable(L, -3);
            // ...
        }
        // ...
    }
    // ...
}

【讨论】:

  • 感谢您的回答。我应该怎么做才能像问题中的lua代码一样?谢谢你给我看一个例子。接触lua才两个星期,不太了解,请谅解。
  • 您通常做对了,但是您在堆栈中索引了错误的项目。如果你从一个简单的表开始,编译,看看它是否有效,然后一点一点地增加复杂性,那么当它坏了你就知道在哪里:D @P.Kwon
  • a[1].b.c.d = 1 这样表达是成功的。顺便说一句,我不知道如何表达 a[1].b.c[1].d = 1 这样的。我们如何表达 a[1].b.c[1].d = 1?真的很紧急。我可以看一个例子吗?
猜你喜欢
  • 1970-01-01
  • 2011-08-07
  • 2012-07-14
  • 2010-12-10
  • 2016-10-17
  • 2011-03-20
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多