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

Is spawn just a coroutine but with coroutine.yield() at the beginning?

I've been hearing explanations on the spawn function being something like: "It runs it's function argument when the thread next yields"

Does this mean that the spawn function would pretty much just look like this?

function spawn(f)
	coroutine.yield()
	coroutine.resume(coroutine.create(f))
end

Or am I missing something? If someone could clear up, or give an example of what they mean by "when the thread next yields", I'd really appreciate it. Thanks!

2 answers

✓ Accepted answer

Yep, you got it.

http://wiki.roblox.com/index.php?title=Function_dump/Functions_specific_to_ROBLOX#Spawn

An alternative to this is coroutines. Spawned functions and coroutines aren't used in the same way. Spawn is used to delay the execution of a functions until the thread yields while coroutines are used to run code immediately on a separate thread. You can't send a Spawned function arguments unless you count this closure:

spawn(function() myfunc(a,b,c) end)

Where as with coroutines, although more complex, can be used to send this.

The prefered ROBLOX syntax for the spawn function is lowercase. "spawn"

spawn(function() end) is not entirely the same as a coroutine as spawn(function() throws errors if there are any in your code and coroutines do not tell you if there are any errors in the code. That is why using coroutine can be helpful if a function can break as the script will continue running because the error is on a different thread.

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