tags:

views:

115

answers:

1

How bad is it in Lua 5.1 to never let a coroutine properly end? In other words, if a coroutine yields but I never resume it, does it leave a lot of state lying around until program completion?

cor=coroutine.wrap(somefunc)

while true do
   done=cor()
   if done then -- coroutine exited with "return true" 
       break
   else -- coroutine yielded with "coroutine.yield(false)"
       if some_condition then break end
   end
end

function somefunc()
    -- do something
    coroutine.yield(false)
    -- do some more
    return true
end 

Depending on some_condition in the pseudocode above, the coroutine might never be resumed, and thus might never properly "end".

Could I do this to dozens of coroutines without having to worry? Is it safe to leave coroutines in this state? Is it expensive?

+7  A: 

The garbage collector can easily determine that the coroutine is unreachable and collect it. I don't know if any of the docs state that this will happen, but I tried the "empirical method":

while true do
  local cor = coroutine.wrap(function() coroutine.yield(false) end)
  cor()
end

Memory usage did not grow over time.

Edit: Google says:

There is no explicit operation for deleting a Lua coroutine; like any other value in Lua, coroutines are discarded by garbage collection. (Page 4 in the PDF)

Uli Schlachter
The PDF is great, thanks for pointing it out.
proFromDover