如何通过可能多次调用的C回调创建1d数字表?该库提供以下回调函数签名:
int callback(int x, int y, int z, void *cb);
假设使用以下值调用了三次:
(1) x=3 y=1 z=4 cb=<ptr>
(2) x=1 y=5 z=9 cb=<ptr>
(3) x=2 y=6 z=5 cb=<ptr>
我希望生成的lua表如下所示:
{ [1]=3, [2]=1, [3]=4, [4]=1, [5]=5, [6]=9, [7]=2, [8]=6, [9]=5 }
以下是相关代码:
int callback(int x, int y, int z, void *cb) {
(lua_State *)L = cb;
// what do I add here? something with lua_pushnumber()?
}
static int caller(lua_state *L) {
lua_createtable(L); //empty table is now on top of stack
exec(callback, L); //can be called any amount of times
return 1;
}
由于回调可能被调用1000次,因此我希望将x,y和z立即添加到表中,以尽可能不消耗整个lua堆栈。
答案 0 :(得分:0)
可能的解决方案是
int index = 1;
int callback(int x, int y, int z, void *cb) {
(lua_State *)L = cb;
lua_pushinteger(L, index++);
lua_pushinteger(L, x);
lua_settable(L, -3);
lua_pushinteger(L, index++);
lua_pushinteger(L, y);
lua_settable(L, -3);
lua_pushinteger(L, index++);
lua_pushinteger(L, z);
lua_settable(L, -3);
}
static int caller(lua_state *L) {
lua_createtable(L); //empty table is now on top of stack
exec(callback, L); //can be called any amount of times
return 1;
}