What is coroutine/spawn, how does it work, and when to use?

The title says everything. I wanna know what is coroutine/spawn(), what does it do, and, when to use it?

I did see the article on coroutines, but it didn’t help too much…

1 Like

There’s some really good tutorials on spawn and coroutine by TheDevKing:

2 Likes

Coroutines and spawns basically create a new thread for you. They’re normally used for while loops so they dont freeze your script.
Example:
If you try using this

while true do
 print("a")
 wait()
end

print("Hello")

It will print “a” but it won’t print “Hello” because the while loop stops everything that goes below it.
Now, if you use

coroutine.wrap(function()
 while true do
  print("a")
  wait()
 end
end)()

print("Hello")

or

spawn(function()
 while true do
  print("a")
  wait()
 end
end)

print("Hello")

It will print “Hello” and “a”.

2 Likes

Coroutines creates a separate thread where you can run your code at without yielding the current thread. Misconception is that this is multi-threading but instead, the reader (… the machine) just goes back and forth through the different threads really quickly.

Spawn does essentially the same however it does have a slight delay before the code is executed.

2 Likes

Wow, that’s insanely useful! I will definitely use this on the future, thank y’all for the replies/your time!