3
votes

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... P.S. I work with Lua 5.3

1
I thought Lua doesn't have arrays - everything is a table. "Arrays" are just syntactic sugar for a table with keys 1, 2, .... - Kerrek SB
This was the case till Lua 4; in Lua 5, a hybrid data structure is used to implement tables which has separate array and hash table parts. Refer ยง4 of lua.org/doc/jucs05.pdf. - legends2k
@Gama It's perhaps possible if you're using Lua 5+ and also if the data you've stored as array elements are amenable to storing them contiguously (an obvious exception, for instance, are tables - since they're stored by reference). I'd suggest you to lookup the Lua implementation code or ask in the Lua mailing list. - legends2k
What do you want to copy the data to? A new Lua table? - ryanpattison
What are you trying to do here exactly? What is the ultimate goal here? How are you planning on using that table you are passed? - Etan Reisner

1 Answers

1
votes

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.