是否可以使用c指针访问Lua表元素? [英] Is it possible to access Lua table elements using a c pointer?

查看:343
本文介绍了是否可以使用c指针访问Lua表元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I call a C function in Lua passing an array/table to it as argument:

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

在C函数中,我得到的大小为:

In the C function I get the size of:

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吗?也许还有另一种直接复制数据的方法?

Instead of iterating over the table is it possible to get the C pointer to that array to use it later for memcpy? Or maybe there is another way to copy data directly?

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

update: What I actually try to do, so maybe someone has a better solution... In my Lua script I do some calculation with the colors. The RGB values of all colors are saved in the one big table (example above would mean one color). This table is passed back to my C code with setColors call, where I normally would copy it using memcpy to a std::vector (memcpy(_colors.data(), data, length); At the moment I do the following:

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

seems for me a lot of code for a simple copy operation... P.S. I work with Lua 5.3

推荐答案

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

No, it is not possible to use a Lua table as a C array via a pointer.

获取值并将其放入Lua表的唯一方法是使用Lua C API.

The only way to get and put values in a Lua table is by using the Lua C API.

这篇关于是否可以使用c指针访问Lua表元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆