Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop a Lua coroutine from outside the function?

Tags:

coroutine

lua

I'm trying to create a dispatcher which schedules multiple coroutines. The dispatcher needs to pause the coroutine, I can't figure out how to do this.

Update Instead of kill, I meant to pause the coroutine from the outside.


2 Answers

You can kill a coroutine by setting a debug hook on it that calls error() from that hook. The next time the hook is called, it will trigger error() call, which will abort 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))

This prints:

2
3
false   coro-kill.lua:6: almost dead
dead
like image 179
Paul Kulchenko Avatar answered May 24 '26 18:05

Paul Kulchenko


library that will yield when you return true in the hook that been set with debug.sethook(co, function() return true end, "y")

the library is enough to create multitask lua system just run require("yieldhook") at very first of your code further info at the git

https://github.com/evg-zhabotinsky/yieldhook

like image 36
Foxie Flakey Avatar answered May 24 '26 17:05

Foxie Flakey