Couroutines questions

Hello, so I was looking at DevWiki, but I do not understand too much, like what should I use it for…

local newThread = coroutine.wrap(function(a, b, c)
    print(a * b + c)

Like, why would I need this, if I can make a function :thinking: are they more efficient?
Is it some kind of loop?


Coroutines are meant for when you need code running simultaneously. When you call a function, it will yield until it returns a value. That means any code below the function call will not run until the function has a value returned. With coroutines, you can run code without yielding. In your scenario, if you were to put print functions below the newThread() call, they would print immediately after the function call. If you were to add a wait() of 3 seconds for example to that function and then print something, any print statement below where you call the coroutine that is intended to run immediately will print before the statement after 3 seconds. Here is an example:

local newThread = coroutine.wrap(function(a, b, c)
    print(a * b + c)
    print("I just printed this after 3 seconds!")
print("I won't wait for the function to finish!")

As a result, you will get the following for your output:

I won't wait for the function to finish!
I just printed this after 3 seconds!

I hope this helps! :slight_smile:


Hey, I knda don’t get it, so, can you be really simple?
example it runs faster than a function
Ut;s because I don’t understand sometimes, like, what’s a yield :confused:

Coroutines do not run faster than a function when it comes to execution time. You could say they allow anything below the coroutine function call (newThread()) to be run faster because it wont yield for the result of the function, but that Is just a weird way to phrase it. Yielding is basically the script stopping until a result is returned. When you do wait(3), the script yields for 3 seconds before continuing. When you run a function outside of a coroutine, it will yield until the return call is sent. For example:

function letsWaitHere()
    print("Ok I am done... returning")
    return "Done"
print("Script is all over")

Your result would be like this:
Script yields (waits) 3 seconds
Ok I am done... returning
The function has returned, so the rest of the script resumes
Script is all over

Wait(val) is the same thing as coroutine.yield(val) so in beginner terms, yielding is the same thing as waiting until something happens.

1 Like

Basically, couroutines doesn’t yields?

Yes exactly. It allows you to run code while letting the code below the coroutine’s call to continue as normal.