How can I stop a Lua coroutine outside of a function?
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 to share