Coroutine - (break vs. coroutine.yield)

Hi!

So the question is… what is the best way to ensure a localscript coroutine has been fully terminated and isn’t lingering in memory but is going to be given to the garbage collector?

So, break or coroutine.yield() or it doesn’t matter? I just want to be fully sure if there’s a difference, which one I should use or if it doesn’t matter and they both will allow this coroutine to get garbage collected:

local c = 0
coroutine.resume(coroutine.create(function()
	while wait(1) do
		print(c)
		c += 1

		if c >= 5  then
					
			print("Break and yield have the exact same effect visually since my variable stops printing/iterating...but is one better to do than the other?")
			coroutine.yield()
			break
		end
	end
end))

There’s a difference. Break will terminate a loop, coroutine.yield will pause a coroutine. Break will throw an error if used outside of a loop. In this specific example, break doesn’t get reached because of the yield though it would get reached if you resumed the thread.

The difference between using either break or yield is the completeness of the coroutine body. When you just break the while loop then you’re asking it to continue with any extra code in the coroutine body and since there’s none the executing body finishes. With yield you’re suspending the thread’s activity.

Since you have no references to the coroutine and it’s not active it will get garbage collected. So really both scenarios do the same thing, just that one does not finish the executing body.

CMIIW I don’t work with coroutines often.

1 Like