Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Coroutine is not resuming suspended thread (no errors)?

So I've been messing around with coroutines, and found a rather strange problem. Apparently when I try to resume a yielded (suspended) coroutine, it doesn't seem to do anything. For this particular example, I tried to make two coroutines with a for loop, that both yield and resume eachother. Here's my code:

-- Create a new thread 
local function thread(f)
	local new=coroutine.create(f)
	coroutine.resume(new)
	return new
end

-- Make these global
local t1,t2

-- This will run first
t1=thread(function()
	for i=1,10 do
		print("FIRST",i)
		coroutine.yield() -- Suspended
		coroutine.resume(t2)
	end
end)

-- This will run second, and at this point, "t1" should be suspended.
t2=thread(function()
	for i=1,10 do
		print("SECOND",i)
		coroutine.resume(t1) -- So resume t1, and yield t2. But if you notice, the code after I yield in "t1" will resume this thread, which should now be suspended.
		coroutine.yield()
	end
end)

So here's the output:

FIRST 1

SECOND 1


But why does it stop at the first iteration? Shouldn't the constant loop of both of these coroutines resuming the other continue the for loop until one of them has terminated and dies?

If anyone can provide an explanation for this, I'd really appreciate it. Thanks.

1 answer

Coroutines are protected
Debugging is painful.

In your code, I'm going to make the awful assumption that t2 doesn't exist by the time the function for t1 tries to resume it. In this case, your coroutine is erroring out because you're trying to resume a nil value, and it becomes very dead.

No error you say? Here comes my real point. Coroutines are run in protected mode - The same thing that handles pcall. As a result, you won't get any errors from them, and you're going to have a hard time debugging.

The moral of this story?
Coroutines suck. Don't use them unless you have a good reason to, and make sure everything is defined before you run them - They don't run quite how you think they do.

This discussion is preserved as it was. New answers, comments, and votes are closed.