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

What is the difference between coroutine.create or spawn?

Hi, I was wondering what was the difference between coroutine.resume(coroutine.create and spawn(function(). Which one is best to use?

coroutine.resume(coroutine.create(function()
	for i = 1, 10 do
		print(i)
	end
end))

/

spawn(function()
	for i = 1, 10 do
		print(i)
	end
end)

1 comment

0

Coroutine has multiple different uses whereas spawn has one. The presented functions are quite the same, my preference for this would be that spawning is a lot quicker and easier to understand

1 answer

spawn internally uses coroutines. There are two major differences between the two however.

spawn schedules the created coroutine to be called after the current step. That means it will be called when the current thread yields or ends. Thus, it won't be executed immediately.

Coroutines on the other hand create a new thread that is called immediately -- the current thread will actually wait for the coroutine to yield or end before continuing itself.

I'd draw a neat little graph demonstraing this procedure but since I'm on my phone, this'll do.

print("spawn start")
spawn(function()
	for i = 1, 10 do
		print("spawn", i)
	end
end)
print("spawn end")

print("coroutine start")
coroutine.wrap(function()
	for i = 1, 10 do
		print("coroutine", i)
	end
end)()
print("coroutine end")

The other difference is that the spawn function doesn't let you work with the actual coroutines and their other functionality.

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