Coroutine lifetime question, why does it stop

I’m confused about the lifetime of coroutines: how exactly is a lifetime of a coroutine tied to the lifetime of a script?

Look at this script which assigns everything to _G:

_G.cortask = function()
	
	while true do
		wait(0.1)
		print("cor")

	end
end

_G.cor = coroutine.create(_G.cortask)
coroutine.resume(_G.cor)

I kinda expected this to keep running even after the Script is destroyed because the scope of the task and the function is now global since I assigend it to _G.

But the coroutine stops when the part which has this script attached is destroyed.

What exactly is happening here? Which part of the coroutine execution is bound to this Script instance?
How is the scope of the coroutine handled in this case?
Why does the coroutine stop if I assigned it to _G when this script gets destroyed?
As I understand it shouldn’t be GC-ed in this case.

The reason I’m asking is that if I call a module library function and I start a coroutine inside some module library function that coroutine will stop working if the Script that called it was destroyed which is error prone.

I think it stops cause you literally destroyed the way for it to function?(aka the script), how would “Code” work without script instance?(or without it being inside a script), not sure tho cause i’ve never really done this type of stuff like destroying the script or parenting it to nil for whatever reason

I’d like to know the details about it, any kind of docs what seems to happen because otherwise I’m just gonna shoot myself in the foot in the future because of this behaviour because it can be non-intutive if a coroutine just dies in some random other module.

It is kinda intuitive that it dies when the script dies, but this behaviour is very unintuitive when the coroutine just dies even when it’s created by some module function in some random module: this can lead to annoying bugs.

This line

You are resuming and running it from this line in this script instance. Hence the behavior seen when this script is destroyed.

Solution is to never attach scripts to parts unless you are sharing it as a free model. Much more easier to control and avoid things like this issue if the script is guaranteed to always run once somewhere in server script service or starter player scripts.

To attach scripts to parts, use collection services and coroutines if the code is yielding.

1 Like