【问题标题】:Is it possible to access Lua table elements using a c pointer?是否可以使用 c 指针访问 Lua 表元素?
【发布时间】:2015-06-30 22:37:30
【问题描述】:

我在 Lua 中调用一个 C 函数,将数组/表作为参数传递给它:

tools:setColors({255,255,0})

在 C 函数中,我得到以下大小:

if (lua_gettop(state) == 2 && lua_istable(state, -1))
{
    lua_len(state, -1);
    int count = lua_tointeger(state, -1);
    lua_pop(state, 1);
}

是否可以获取指向该数组的 C 指针,以便稍后将其用于memcpy,而不是遍历表?或者也许有另一种方法可以直接复制数据?

更新: 我实际上尝试做的事情,所以也许有人有更好的解决方案...... 在我的 Lua 脚本中,我对颜色进行了一些计算。所有颜色的 RGB 值都保存在一张大表中(上面的示例表示一种颜色)。该表通过 setColors 调用传递回我的 C 代码,我通常会使用 memcpy 将其复制到 std::vector (memcpy(_colors.data(), data, length); 目前我执行以下操作:

    // one argument with array of colors (triple per color)
    lua_len(state, -1);
    int count = lua_tointeger(state, -1);
    lua_pop(state, 1);

    for (int i=0; i < count / 3; i++)
    {
        ColorRgb color; // struct {uint8_t red, uint8_t green, uint8_t blue}
        lua_rawgeti(state, 2, 1 + i*3);
        color.red = luaL_checkinteger(state, -1);
        lua_pop(state, 1);

        lua_rawgeti(state, 2, 2 + i*3);
        color.green = luaL_checkinteger(state, -1);
        lua_pop(state, 1);

        lua_rawgeti(state, 2, 3 + i*3);
        color.blue = luaL_checkinteger(state, -1);
        lua_pop(state, 1);
        _colors[i] = color;
    }

对我来说,一个简单的复制操作似乎有很多代码...... 附言 我使用 Lua 5.3

【问题讨论】:

  • 我以为 Lua 没有数组——一切都是表格。 “数组”只是键为 1、2、...的表的语法糖。
  • 在 Lua 4 之前都是这样;在 Lua 5 中,混合数据结构用于实现具有单独数组和哈希表部分的表。请参阅lua.org/doc/jucs05.pdf 的§4。
  • @Gama 如果您使用 Lua 5+ 并且如果您存储为数组元素的数据可以连续存储它们(一个明显的例外,例如,表 -因为它们是通过引用存储的)。我建议您查找 Lua 实现代码或在Lua mailing list 中询问。
  • 您要将数据复制到什么位置?一个新的 Lua 表?
  • 你到底想在这里做什么?这里的最终目标是什么?你打算如何使用你通过的那张桌子?

标签: c lua


【解决方案1】:

不,不能通过指针将 Lua 表用作 C 数组。

在 Lua 表中获取和放入值的唯一方法是使用 Lua C API。

【讨论】:

    猜你喜欢
    • 2021-01-26
    • 1970-01-01
    • 2011-06-04
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    相关资源
    最近更新 更多