We use cookies on this site to enhance your user experience

2 min

Code threading is a method that allows two or more pieces of code to run at once. Threading becomes necessary when, for example, you want to run two while loops simultaneously:

This naive attempt fails because lines of code are run sequentially — this means the first loop never stops, so the second loop never gets executed.

Constructing a Thread

In Roblox, the spawn() function can be used to start a function in a new thread:

At the moment, this thread method isn’t providing anything more than a non-threaded while loop, but it can be expanded upon to run two loops in parallel:

For symmetry, the second loop can also be threaded:

Threading Considerations
  • Having many threads will eventually cause lag in a game, so it's best to keep thread count to a minimum by optimizing code and combining all functionality that can be mixed.
  • Just like functions, threads take on the environment of the parent context where they were created. So, any existing variables of its parent stack (local or global) will fall into the new thread's environment as well.

  • lua
  • threading
  • thread