Coroutine "cannot resume dead coroutine"

I’m trying to make a function with a infinite loop run whenever character added, and whenever the character respawned it’ll start this function from the beginning.

the following code works, but it shows this error for some reason.

Players.PlayerAdded:Connect(function(plr)
	local mainloop
	
	plr.CharacterAdded:Connect(function(chr)
		mainloop = coroutine.create(MainGameLoop)
		if coroutine.status(mainloop) ~= "dead" then
			coroutine.resume(mainloop, plr, chr)
		end
	end)
	plr.CharacterRemoving:Connect(function(chr)
		coroutine.close(mainloop)
	end)
end)

image
Even though I check if it’s dead or not it shows this error.

what would be a better way to do it?

1 Like

I would suggest to print the coroutine status before checking it with a statement, I would also exchange coroutine.status with coroutine.running to better ensure that it isn’t dead and is able to keep resuming.

1 Like

it always prints “suspended”, also how do you exchange the coroutine.status with coroutine.running? and which coroutine it returns if there are more than one coroutine running?

1 Like

For exchanging between them you just switch them in the argument of: if coroutine.status(mainloop) ~= "dead" then to if coroutine.running(mainloop) ~= "dead" then , also it returns the running coroutine which I assume is the closest thread that is running.

1 Like

coroutine.running() doesn’t take any arguments, also it returns a thread and not a string, meaning this statement will always be true because coroutine.running() will nerver return the string “dead”.
image
unless i miss something?

2 Likes

coroutine.running() is for getting the thread object of the thread calling it