I want to call a function in Lua from a C library, but done asynchronously.
I have some Lua code that looks like this:
l = require "mylib"
l.subscribe(function ()
print("Called")
error("This is an error")
end)
mylib is implemented using the Lua C API. It looks a bit like this.
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;
// store c in callback_functions
}
// foo is registered as a callback to another C lib and
// is called occasionaly
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);
// Check ret...
}
}
The message in the callback is printed, however the error shows up in the wrong place (it says it was caused by some unrelated function). I assume this is because the Lua state has changed.
What is the proper way to do this?