This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Luca_S's profile picture

How to kill a coroutine?

Started by Luca_S, 15 November 2014 - 02:47 PM
Luca_S #1
Posted 15 November 2014 - 03:47 PM
Is there a way to "Kill" a coroutine?

I mean, you could stop it from continuing, but the status would be "suspended" Anyway. So is there a way to do something like this


function function1()
  while true do
    ev,key = os.pullEvent("key")
    print(key)
  end
end
function function2()
  while true do
    ev,button,x,y = os.pullEvent("mouse_click")
    print(x)
    print(y)
  end
end
co1 = coroutine.create(function1)
co2 = coroutine.create(function2)
co1runs = 10
while true do
  ev,ev1,ev2,ev3 = os.pullEvent()
  if co1runs > 0 then
    coroutine.resume(co1,ev,ev1,ev2,ev3)
    co1runs = co1runs-1
  else
    coroutine.kill(co1) --my unknown/not existing function
    coroutine.status(co1) --should return "dead" know
  end
  coroutine.resume(co2,ev,ev1,ev2,ev3)
end

And as said, sure the coroutine wont run, but the status is "suspended".

This would give you the Ability, that an OS User couldnt resume a stopped program from the terminal(LUA-Program). BTW couldnt you use co1:resume(ev,ev1,ev2,ev3) too?
KingofGamesYami #2
Posted 15 November 2014 - 10:42 PM
No, but if the co-routine returns, it "dies". You can accomplish this by editing the co-routine in question to return when it receives an event, which you can make using os.queueEvent or simply insert via your coroutine managing code.
Bomb Bloke #3
Posted 15 November 2014 - 10:46 PM
I'd remove all references to your co-routines, making it impossible to resume them, and also making it possible for the garbage collector to delete them entirely.

Best way to do this is to declare them as local to your script:

local co1 = coroutine.create(function1)
local co2 = coroutine.create(function2)

Once the script ends, the variables holding the coroutine pointers are then discarded. If you wanted to discard them earlier than that, simply discard the pointers yourself:

co1, co2 = nil, nil