The title says it all. The wiki is not good at explaining it. Can you explain it and give examples?
Thanks
Coroutines are basically a global that is used for doing things without yielding the rest of the script. It acts as a whole new script, except in one script. For example:
while wait() do print("Hello world!") end print("Bob the Builder!")
This would not work as the while wait() loop would keep on looping and never get on to the rest of the script and print "Bob the Builder!" But when we add a coroutine
, it changes everything.
coroutine.wrap(function() while wait() do print("Hello world!") end end) print("Bob the Builder!")
Now it would print "Hello world!" and "Bob the Builder!"
Another example is:
coroutine.wrap(function() wait(5) workspace:ClearAllChildren() end print("Hello world!")
Without a coroutine, it would wait 5 seconds and then print "Hello world!", but with a coroutine, it prints straight away.
You can also give coroutines variables. For example:
local newThread = coroutine.create(function() print("Hola!") end) coroutine.resume(newThread)
Wait, why are we resuming the coroutine you may ask. That's because coroutines can be paused by using coroutine.yield()
. For example:
local newThread = coroutine.create(function() while wait() do print("Hola!") end end) wait(math.pi) coroutine.yield(newThread)
This would yield the thread (coroutine) after math.pi seconds (3.14159, etc.)
You can ALSO use arguments and parameters with coroutine.wrap()
. For instance:
local newThread = corutine.wrap(function(message) print(message) end) newThread("Namaste!")
Please upvote and accept this answer if it helped.