[英]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? 我想传递一个包含从Lua到C的数字的列表并在C中访问它。我该怎么做?
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. 我想将它发送到C并将此表存储在C中的数组中。
I sent it using: 我发送它使用:
quicksort(x)
where quicksort
is the function I have defined in C. quicksort
是我在C中定义的函数。
How can I access the x
in C? 如何在C中访问x
?
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
. 您可以使用lua_getfield
或lua_gettable
对其进行索引。
Traversing the table with lua_next
, you can populate your array in C if you need to; 使用lua_next
遍历表,如果需要,可以在C中填充数组; although, for an array, simply iterating from 1 to #t
should suffice. 虽然,对于一个数组,只需从1迭代到#t
就足够了。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.