Jump to content




How to kill a coroutine?


  • You cannot reply to this topic
2 replies to this topic

#1 Luca_S

  • Members
  • 407 posts
  • LocationGermany

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?

#2 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

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.

#3 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

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






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users