How can I stop a Lua coroutine outside of a function?

I am trying to create a dispatcher that schedules multiple coroutines. The dispatcher needs to suspend the coroutine, I can't figure out how to do that.

Update Instead of killing, I wanted to suspend the coroutine outside.

+3


source to share


1 answer


You can kill a coroutine by setting a debug hook for it, which calls error()

from that hook. The next time the hook is called, it will invoke a call error()

that will interrupt the execution of the coroutine:

local co = coroutine.create(function()
  while true do print(coroutine.yield()) end
end)
coroutine.resume(co, 1)
coroutine.resume(co, 2)
debug.sethook(co, function()error("almost dead")end, "l")
print(coroutine.resume(co, 3))
print(coroutine.status(co))

      



Prints:

2
3
false   coro-kill.lua:6: almost dead
dead

      

+1


source







All Articles