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)
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()
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)()
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")
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)()
2:00:00 > Bye
2:00:00.029 > Hello
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.
1 comment
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.