Yielding from within a C function


I've got a C function I want to implement as a coroutine called from Lua, but it seems that just calling coroutine.yield() from C doesn't work and overflows the Lua stack for some reason. Does anyone know how I can implement this better than using this example?

err = pd->lua->callFunction("coroutine.yield", 1, &outErr);

If it helps, I'm calling coroutine.create() on the C function to get the thread, not sure if that makes a difference.

All right, I think I figured it out:
pd->lua->callFunction() actually calls the function from a Lua context (of course), but that poses a problem for luaB_yield, which calls lua_yieldk.
Since coroutine.yield is called "from Lua", luaB_yield catches it and gives an error since there's a "non-yieldable C call" in the stack.

The only solution I can think of is for the firmware to give more direct access to lua_yieldk via a new function, or maybe the "coroutine.yield" could be intercepted inside pd->lua->callFunction and divert the function to directly call lua_yieldk instead of caing it from a Lua context.

I'm not sure exactly what your usecase is, but you might be able to get away with using this C library for coroutines: [C/C++] Coroutines Library for Playdate