【问题标题】:Create 1d numeric lua table from C callback从 C 回调创建一维数字 lua 表
【发布时间】: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 堆栈。

【问题讨论】:

    标签: c lua lua-table lua-api


    【解决方案1】:

    一个可能的解决方案是

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 2021-02-25
      • 2021-10-05
      • 2012-07-14
      • 2013-12-09
      相关资源
      最近更新 更多