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