Threading is a tool that allows two or more pieces of code to run at once. You cannot expect two while loops (as shown below) to run simultaneously in the same thread. A naive attempt at this shown below, fails
while true do wait() print("Hello World!") end while true do wait() print("Goodbye World!") end
Since lines of code are run in sequentially, and the first loop never stops, the second loop never gets executed
Constructing a thread
There is a specific function,
spawn, which can be used to start a function in a new thread:
Of course, at the moment the thread isn’t getting us anything we didn’t already get with the while loop
Running code simultaneously
We can now use this code to solve our original problem of running two pieces of code in parallel:
For symmetry, we could put the goodbye code in a thread too:
function helloThread() while true do print("Hello World!") wait() end end function goodbyeThread() while true do print("Hello World!") wait() end end -- start both threads in parallel spawn(helloThread) spawn(goodbyeThread)
Information to consider
spawn creates a new thread. Having many threads will eventually cause lag in a game, so it is best to try and keep the thread count to a minimum by optimizing code and combining all that can be mixed.
Another important fact to remember is that just like functions, threads take on the environment of their parent context of where they were created. So any existing variables of its parent stack, local or global, will fall into the newly created coroutine’s envionrment as well.
Articles/Beginners Guide to Coroutines