Yes, but, most of the time this will be not the best solution to a problem.
As a simple example, two Script objects will run at the same time. Each Script object is given its own "thread", or, as Lua calls it, coroutine (routine being a piece of a program and co indicating that multiple are working together, as in coworker)
Coroutines are not true threads. Only one coroutine can execute at a time; ROBLOX just quickly switches between them. Many coroutines at once move very slowly, which is just one reason to avoid using them too much.
Here is the PIL description of coroutines:
A coroutine is similar to a thread (in the sense of multithreading): a line of execution, with its own stack, its own local variables, and its own instruction pointer; but sharing global variables and mostly anything else with other coroutines.
Lua uses the coroutine
library to create new coroutines. Coroutines Wiki Article
1 | routine = coroutine.create( func ) |
2 | coroutine.resume( routine ) |
coroutine.create
makes a new coroutine, given a function.
coroutine.resume
"unpauses" (resumes "playback") of a coroutine object / starts a coroutine.
There are other controls like coroutine.yield
that let coroutines produce results.
If you're repeatedly resume
ing the same function, you can instead use coroutine.wrap
.
1 | playRoutine = coroutine.wrap( func ) |
coroutine.wrap
returns a function which will resume your coroutine each time it's called (which will usually just be once)
ROBLOX provides two new functions to do this in a little less code.
spawn(func)
will create and run a coroutine with a given function. Spawn
delay(func, time)
will, after time
seconds, create and run a coroutine with the given function. Delay
Here are some examples using spawn
:
03 | game.Workspace.A.BrickColor = BrickColor.new( "Bright blue" ); |
05 | game.Workspace.A.BrickColor = BrickColor.new( "Black" ); |
12 | game.Workspace.B.BrickColor = BrickColor.new( "Bright red" ); |
14 | game.Workspace.B.BrickColor = BrickColor.new( "Black" ); |
I mentioned at the beginning that usually coroutines aren't the best solution to a problem. For example, with the above example, it makes much more sense to combine the two into one function:
01 | function redsAndBlues() |
03 | game.Workspace.A.BrickColor = BrickColor.new( "Bright blue" ); |
04 | game.Workspace.B.BrickColor = BrickColor.new( "Bright red" ); |
06 | game.Workspace.A.BrickColor = BrickColor.new( "Black" ); |
07 | game.Workspace.B.BrickColor = BrickColor.new( "Black" ); |
See Also: https://scriptinghelpers.org/questions/11836/can-one-script-run-many-items for more complicated comparison of with coroutine and without