【发布时间】:2019-10-23 09:34:37
【问题描述】:
如何从可能被多次调用的 C 回调创建一维数值表?该库提供以下回调函数签名:
int callback(int x, int y, int z, void *cb);
假设它被调用了 3 次,值如下:
(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 堆栈。
【问题讨论】: