从C回调创建1D数字Lua表

如何从可能调用多次的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;
  // 在此添加什么?使用 lua_pushnumber() 添加内容?
}

static int caller(lua_state *L) {
  lua_createtable(L); // 创建一个空表,它现在位于堆栈顶部
  exec(callback, L); //可调用任意次数
  return 1;
}

由于回调可能会被调用数千次,如果可能,我希望立即将 x、y 和 z 添加到表格中,以免占用整个 Lua 堆栈。

点赞
用户2420301
用户2420301

可能的解决方案如下:

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); //创建一个空表并将其置于栈顶
  exec(callback, L); //可以调用任意次
  return 1;
}
2020-02-26 12:19:10