Rahul Rahul - 9 days ago 5
C Question

How to pass Table(list of numbers) from Lua to C and access it

I want to pass a list containing numbers from Lua to C and access it in C. How can I do it?

Suppose I have the following Table:

x = {1, 2, 3, 9, 5, 6}


I want to send it to C and store this table in array in C.

I sent it using:

quicksort(x)


where
quicksort
is the function I have defined in C.

How can I access the
x
in C?

Answer

The table you pass to the function will be on the function's stack. You can index it by using lua_getfield or lua_gettable.

Traversing the table with lua_next, you can populate your array in C if you need to; although, for an array, simply iterating from 1 to #t should suffice.

Some example utility code (untested):

int* checkarray_double(lua_State *L, int narg, int *len_out) {
    luaL_checktype(L, narg, LUA_TTABLE);

    int len = lua_objlen(L, narg);
    *len_out = len;
    double *buff = (double*)malloc(len*sizeof(double));

    for(int i = 0; i < len; i++) {
        lua_pushinteger(L, i+1);
        lua_gettable(L, -2);
        if(lua_isnumber(L, -1)) {
            buff[i] = lua_tonumber(L, -1);
        } else {
            lua_pushfstring(L,
                strcat(
                    strcat(
                        "invalid entry #%d in array argument #%d (expected number, got ",
                        luaL_typename(L, -1)
                    ),
                    ")"
                ),
                i, narg
            );
            lua_error(L);
        }
        lua_pop(L, 1);
    }

    return buff;
}
Comments