Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What are coroutines and how do I use them? Help

Asked by 3 years ago

So recently I stumbled upon this thing called coroutines. I know that they're supposed to make several things happen at once, when should I use them, how do I use them. This is what I know:

  • Some times you need to use end)()

  • They are used to make more than one thing happen at once

0
Try using the things you know a little about of and ask anything that you really need help with. It's the best way to learn and know how it works. DiamondComplex 285 — 3y

1 answer

Log in to vote
2
Answered by
imKirda 4491 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago

Coroutines spawn threads inside of a script just like spawn function, only difference between spawn and coroutine is that spawn automatically creates 'wait' when created.

To create a coroutine you use coroutine.create.

local myCoroutine = coroutine.create(function()
    print("Coroutine worked")
end)

This created a coroutine but the coroutine is not running yet, to run it you use coroutine.resume which resumes your coroutine, example:

coroutine.resume(myCoroutine)

--Output -- > Coroutine worked

Now there is a function called coroutine.wrap which asaik makes it easier to use, here is example:

local myCoroutine = coroutine.wrap(function()
    print("hello")
end)

And when using wrap, to start the coroutine all you have to do is:

myCoroutine() -- Plays the coroutine

--instead of

coroutine.resume(myCoroutine)

The reason why as you said you can use end)() is because you must start the coroutine so this

local myCoroutine = coroutine.wrap(function()
    print("hello")
end)

myCoroutine()

is same as

local myCoroutine = coroutine.wrap(function()
    print("hello")
end)() -- With brackets

There are also other functions, those are just basics. As you know it spawns other thread in same script so

local myCoroutine = coroutine.wrap(function()
    wait(5)
    print("bye")
end)

myCoroutine()
print("hello")

--Output
2:00:00 > hello
2:00:05 > bye

But i assume you understand this. Here is difference from spawn function as i mentioned before, it automatically creates wait function there, example here:

spawn(function()
    print("Hello")
end)

coroutine.wrap(function()
    print("Bye")
end)() -- The brackets instantly starts it

--Output
2:00:00 > Bye
2:00:00.029 > Hello
-- As you see the spawn function had delay of `wait(0.029)` (Which is default wait number if argument is nil)

Here is devforum about coroutines, this is where you should learn about them because i am really not good at explaining so sorry about that but i hope it helped atleast a bit.

Ad

Answer this question