To defer a one task from another, for example, if you want to run 2 while loops.
while task.wait(0.1) do
print("loop 1 is on.")
end
while task.wait(0.1) do
print("loop 2 is on.")
end
This code will only print “loop 1 is on.” Because while loops yeild, basically, the while loop has to finish/stop before the next block of code can be ran.
You can use coroutines to run them at the same time, heres an example:
coroutine.wrap(function()
while task.wait(0.1) do
print("loop 1 is on.")
end
end)()
while task.wait(0.1) do
print("loop 2 is on.")
end
Here we wrap it in a coroutine, making a seperate thread, so while the first runs, the code can continue.
They are useful if you want to run code at the same time, or if your having timing issues with like animations for example.
Its just a good tool to know. Test these blocks of code out and see what you get.
there is also other functions in coroutines, though im too lazy to go over them, read some documentation, might be more examples and explanations there.
Its fine to use them, of course keeping everything in 1 thread complicates everything less, but if needed, its fine to use coroutines, even encouraged sometimes.
There is task.spawn() but it doesn’t really differ to coroutine.wrap().
Hope this helps!