I checked out the scripting glossary and I found out that a Coroutine is basically a script running inside a script..
"A coroutine is a routine outside the main routine of the script. It executes its own code whilst the main (script's) routine executes as well, therefore having two routines by one thread - multitasking! You aren't limited to 'only' have one coroutine."
I want to know how to use Coroutines, how would I go about doing so?
To use coroutines, you are going to want to use the coroutine
library.
function some_func() while wait(2) do print('hi') end end local routine = coroutine.create(some_func) coroutine.resume(routine) -- This doesn't yield print("Test") -- prints instantly
You can also make use of the Spawn
and Delay
functions to easily create another routine without all of the hassle of the coroutine
library.
Spawn(function() while wait(2) do print('hi') end end) print("Test") -- same effect as above
Let's say you want two functions:
function hi() for i=1, 100 do print "HELLO" wait(.1) end end function spam() for i=1, 100 do Instance.new("Part", workspace).Position = Vector3.new(0, 100, 0) wait() end end
If we tried this, we would get a 10 second delay before it started raining bricks, because the script wants to finish printing HELLO first:
hi() spam()
This is where Spawn(), Delay(), and coroutines come in handy:
Spawn(hi()) -- Spawn tells the script to send the function to the task scheduler, and moves on with the rest of the script. spam()
Delay(1, hi()) -- Just like spawn, except, in this example, there is a 1 second delay before hi goes. spam()
Explaining coroutines probrobly wouldn't fit on this webpage, so see if this helps.
(Just remember with coroutines that you can't reuse a "dead" coroutine)