✓ Accepted answer
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.
- Coroutines created (but not stored in a variable) are marked for garbage collection.
collectgarbage()
print("Before coroutines:", collectgarbage("count"))
for i = 1, 1000 do
coroutine.resume( coroutine.create(function() end) )
end
collectgarbage()
print("After coroutines:", collectgarbage("count"))
prints:
Before coroutines: 27.6806640625
After coroutines: 27.458984375
- Coroutines created and stored in a variable will be marked for garbage collection after it reaches the end of its lifetime (much like any other variable):
collectgarbage()
print("Before coroutines:", collectgarbage("count"))
for i = 1, 1000 do
local cor = coroutine.create(function() end )
coroutine.resume(cor)
end
collectgarbage()
print("After coroutines:", collectgarbage("count")
prints:
Before coroutines: 27.7314453125
After coroutines: 27.509765625
- Coroutines that are stored in a variable that has not yet reached the end of its lifetime will NOT be marked for garbage collection, regardless of whether or not it has stopped.
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
1 comment
Exactly what I was looking for, thank you!!