能否使用C指针访问Lua表元素?

我在 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(),数据,长度);)。 目前我是这么做的:

    // 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;
    }

这对于简单的复制操作来说是很长的代码... P.S. 我使用 Lua 5.3。

点赞
用户107090
用户107090

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

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

2015-06-30 11:54:05