Say I have this coroutine:
1 | coroutine.resume(coroutine.create( function () |
2 | for i = 1 , 10 do |
3 | print ( "hi" ) |
4 | end |
5 | 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.
01 | collectgarbage () |
02 | print ( "Before coroutines:" , collectgarbage ( "count" )) |
03 |
04 | for i = 1 , 1000 do |
05 | -- I don't have to resume the coroutine for it to be marked for garbage collection |
06 | coroutine.resume( coroutine.create( function () end ) ) |
07 | end |
08 |
09 | collectgarbage () |
10 | print ( "After coroutines:" , collectgarbage ( "count" )) |
prints:
1 | Before coroutines: 27.6806640625 |
2 | After coroutines: 27.458984375 |
01 | collectgarbage () |
02 | print ( "Before coroutines:" , collectgarbage ( "count" )) |
03 |
04 | for i = 1 , 1000 do |
05 | local cor = coroutine.create( function () end ) |
06 | -- Again, I don't have to run the coroutine for it to be marked for garbage collection |
07 | coroutine.resume(cor) |
08 | end |
09 |
10 | collectgarbage () |
11 | print ( "After coroutines:" , collectgarbage ( "count" ) |
prints:
1 | Before coroutines: 27.7314453125 |
2 | After coroutines: 27.509765625 |
01 | collectgarbage () |
02 | print ( "Before coroutines:" , collectgarbage ( "count" )) |
03 |
04 | local t = { } |
05 |
06 | for i = 1 , 1000 do |
07 | table.insert(t, coroutine.create( function () end ) ) |
08 | coroutine.resume(t [ i ] ) |
09 | end |
10 |
11 | collectgarbage () |
12 | print ( "After coroutines:" , collectgarbage ( "count" )) |
prints:
1 | Before coroutines: 27.7998046875 |
2 | 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.