如何从 C 代码中异步调用 Lua 回调?

我想要从一个 C 库中异步地调用 Lua 中的一个函数。

我的一些 Lua 代码如下所示:

l = require "mylib"

l.subscribe(function ()
  print("Called")
  error("This is an error")
end)

mylib 是使用 Lua C API 实现的。它长这样:

struct cb {
  int ref;
  lua_State *state;
}

int number_callbacks;
struct **cb callback_functions;

static int subscribe(lua_State *L) {

  lua_settop(L, 1);
  luaL_checktype(L, 1, LUA_TFUNCTION);

  struct cb c;
  c.ref = luaL_ref(L, LUA_REGISTRYINDEX);
  c.state = L;

  // 把 c 存入 callback_functions 中
}

// foo 作为另一个 C 库的回调被注册,有时会被调用
static void foo(int callback_code) {

   for (int i = 0; i < number_callbacks; i++) {

     struct cb c = callback_functions[i];
     lua_rawgeti(c->state, LUA_REGISTRYINDEX, c->ref);
     lua_pushinteger(c->state, callback_code);

     int ret = lua_pcall(c->state, 1, 0, 0);

     // 检查 ret...
   }
}

回调函数中的消息会被打印出来,但 error 函数显示在错误的地方(它说是由某个不相关的函数引起的)。我猜这是因为 Lua 状态发生了改变。

正确的方法是什么?

点赞