Search code examples
luacoroutine

Lua debug hooks seems to prevent the coroutine from working


So, I'm trying to build a multitasking system in lua that hands control back to the main thread at regular intervals. The issue is that debug.sethook seems to cause the coroutines to die immediately when you set it to call coroutine.yield.

Setting to do something else appears to work properly.

o=coroutine.create(function()
   print("Hello")
   print("goodbye")
end)
debug.sethook(o,coroutine.yield,"l",1)
coroutine.resume(o)--No output here
print(coroutine.status(o))--prints dead.

What am I doing wrong?

Edit: It happens in a near minimal context as well, so I simplified the example code.


Solution

  • If you print the result of resume call, you'll see something like false attempt to yield across a C-call boundary, so the execution fails, as you are trying to yield from the debug hook, which you can't do (you'll need to return from the debug hook). You can resume from the debug hook into a different coroutine and yield from there, but you can't yield from the hook.

    Maybe a different solution can be recommended if you explain what you are trying to do (in an edit).