Question about coroutines?

I have a OOP script, and a function in it which creates a coroutine that changes an unrelated “self” variable after waiting for a few seconds.

Now, this coroutine is also saved as a “self” variable so it can be accessed by other functions by calling self.coroutine1.

If I were to yield the coroutine while it is using wait(), it should stop waiting until resumed.

If I would set self.coroutine1 to nil after yielding the coroutine, and then overwrite it with a new coroutine, would the old coroutine get collected by the garbage collector immediately?

Could this cause performance issues?

Yes, it will be cleaned up. It won’t be immediate (the GC runs periodically), but it will happen.

local function ABC()
   while true do

   local abc = coroutine.create(ABC)
   for i = 1,3 do
-- 'abc' out of scope here

In that scenario, once abc goes out of scope or is set to nil, the GC will be able to clean up the coroutine. Similarly, if you were to overwrite abc to a different coroutine, the old one would still be cleaned up since all of its references were lost.

1 Like