Multithreading

Prequisites:
-Variables

-Functions

-Returning

Sometimes, you might want to run 2 or more parts of a script at the same time. Fortunately, there is multithreading for that! There are 2 ways you can do that (besides connecting and with functions), those 2 days being spawn/delay and coroutine.

How to use them
Spawn is used like this while coroutine is used like this Note that spawn directly runs the script you give it while with coroutine, you can save the script to run at any time. This also comes with the downside that it needs to be triggered like a function.

How to save multithread code with coroutine
First, you make a variable assigned to your coroutine. I named mine Coroutine (starting with a capital, dont name it in all lowercase, that name is taken) Note that I did not put the at the end. the is what runs the coroutine.

Now, you can run it whenever you wish like so!

Coroutines with parameters
An additional upside to using coroutines instead of spawn is that coroutines can take parameters just like functions can! This coroutine will add the two numbers you give it and print it!

When to use which
You should almost always use coroutine as it is newer and has more abilities. The only time that you should use spawn over coroutine is whenever there is a chance of an error. Even the slightest chance of an error and you should use spawn (Or fix your script! or use pcalls!). '''If coroutine runs into an error, it go into a state known as 'dead'. It is exactly what it sounds like.'''

Please note that both coroutine and spawn can have a small delay at times. This (as far as I know) is due to how roblox processes scripts and can take anywhere from about 0.03 to 0.5 seconds. Also, coroutine is slightly faster than spawn although this "slightly" can change drastically if there is lag.