Say I have this coroutine:
coroutine.resume(coroutine.create(function() for i=1,10 do print("hi") end end))
(Note, I'm not using that specifically, it's just an example) Once it prints "hi" 10 times, what happens to the coroutine? Does it cease to exist? Does it just sit there, consuming useful Data? It's one of the reasons I'm scared to use them. Thanks!
Depending on how and where the coroutine is created, the garbage collector may or may not automatically collect it.
Roblox automatically collects garbage at a set interval. For the purposes of simulation, I'm collecting garbage manually (via collectgarbage()
) Since collectgarbage
is disabled in Roblox Lua, you may use an online sandbox like this one.
collectgarbage() print("Before coroutines:", collectgarbage("count")) for i = 1, 1000 do -- I don't have to resume the coroutine for it to be marked for garbage collection coroutine.resume( coroutine.create(function() end) ) end collectgarbage() print("After coroutines:", collectgarbage("count"))
prints:
Before coroutines: 27.6806640625 After coroutines: 27.458984375
collectgarbage() print("Before coroutines:", collectgarbage("count")) for i = 1, 1000 do local cor = coroutine.create(function() end ) -- Again, I don't have to run the coroutine for it to be marked for garbage collection coroutine.resume(cor) end collectgarbage() print("After coroutines:", collectgarbage("count")
prints:
Before coroutines: 27.7314453125 After coroutines: 27.509765625
collectgarbage() print("Before coroutines:", collectgarbage("count")) local t = {} for i = 1, 1000 do table.insert(t, coroutine.create(function() end) ) coroutine.resume(t[i]) end collectgarbage() print("After coroutines:", collectgarbage("count"))
prints:
Before coroutines: 27.7998046875 After coroutines: 856.1953125
it just stops that piece of code when its done. you honestly can run corountines in any part of the script, not just the beggining.