Can someone explain to me what spawn functions/coroutines are in detail like I'm 3?

What are spawn functions and how/when do I use them? I still don’t quite understand it despite referring to the Developer Hub. What are threads that it creates? The differences between it and coroutines? Would really appreciate a good explanation, thanks in advance.

You use coroutines or the spawn function when to want to run some code that will potentially yield, hence using them will stop yielding. For, example if you have a script with this:

while true do
    wait(1)
end

print("Done") --[[ this line will never get executed because the  while 
                 loop yields the thread forever or until you break from
                 the loop]]--

--to solve this problem you can use a coroutine or spawn like this:

coroutine.wrap(function()
   while true do
       wait(1)
   end
end)()
print("Done") 
--[[  trying running in two different scripts and in the one where the coroutine 
      is used the message Done will be printed
]]-- 

In some cases you can work around this by creating new scripts, but this is not always feasible.

The main difference between the two is that the spawn function adds a delay before it executes the instructions inside of it, although it is recommended that you never use it here is the post why: Coroutines V.S. Spawn()... Which one should I use? - #8 by evaera. Basically when you start to use more spawns the delay will also become longer.

However, there is also a downside to using coroutines as they obscure the stack trace for errors generated making debugging difficult, this just means if you run something in a coroutine it will not show where the actual error is generated it will just point to line where the coroutine begins.
For example if you try running the following code:

coroutine.wrap(function()
    print("Hey")
    print(1+"c") --Error
    print("Ok")
end) ()

The error will be generated but points to line 1 instead of line 3, basically destroying the stack trace for the error, now this may not seem like a big deal, but it can get really confusing when you start calling to external modules because whenever you click on the error in the output window it will carry you to the coroutine and not the acutal error.

Personally I never use either I create my own custom thread class which is similar to one found here: https://github.com/Sleitnick/AeroGameFramework/blob/master/src/ReplicatedStorage/Aero/Shared/Thread.lua. Another feasible option: Promises and Why You Should Use Them

4 Likes

Ah thank you for the explanation. Truly helped!

1 Like