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

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

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

      

In the C function, I get the size:

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

      

Rather than iterating over the table, can I use a C pointer to this array for later use for memcpy

? Or maybe there is another way to copy the data directly?

update: What I am actually trying to do, maybe someone has a better solution ... In my Lua script, I am doing some calculations with colors. The RGB values ​​of all colors are stored in one large table (the example above means one color). This table goes back to my C code with a call to setColors, where I usually copy it using memcpy to std :: vector ( memcpy(_colors.data(), data, length

); At the moment I am doing 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;
    }

      

there is a lot of code for me for a simple copy operation ... Postscript I am working with Lua 5.3

+3


source to share


1 answer


No, you cannot use a Lua table as a C array using a pointer.



The only way to get and put values ​​into a Lua table is to use the Lua C API.

+1


source







All Articles