Roblox uses a thread scheduler to allow multiple scripts to execute in parallel. You can use this to your advantage to run two pieces of code in parallel in the same script. Roblox's thread scheduler is exposed through the functions Spawn, Wait, and Delay.
For the rest of this article, the word "Task" is used to refer to a coroutine being managed by the thread scheduler.
There are two ways to queue tasks into the thread scheduler:
When roblox runs a wait function (or any other YieldFunction), it pauses the current task, queues it up for later, then looks for other waiting tasks (ie another script, or an event handler), and resumes the next most important. There is no other way to switch task - if you've queued a task with Spawn, you have to wait() in order to make it run:
Additionally, new tasks can be run when a queued task terminates - with no wait() in the above code:
ypcall queues a task, and then pauses the current task until either the queued task completes or errors
The following code shows a roblox thread scheduler written in lua that (seems to) behave in the same way as the builtin one:
This does not cover: