简体   繁体   中英

Is it possible to access Lua table elements using a c pointer?

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

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

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

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?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM