Threading Basics

Explanations for spawn, delay and the coroutine library.

by Iplaydev

Author Avatar

Threading is an integral part of programming. From loading assets while playing the game, or running a game loop for a FPS, threading can be used in many cases.

What is Threading?

Threading is where you create a thread which can be used to run code without stopping the entire script. You can easily create a thread in RBLX Lua by doing

spawn(function()
    -- code
end)

This, in itself wouldn't do anything. However, if you put a while loop inside of the spawn, you can run code before and AFTER the while loop is set. For example,

print("Hello world!") -- prints

spawn(function()
    while wait() do
        -- i am of the code variety
    end
end)

print("Hello world!") -- still prints

Delayed threading

What if, instead of making a thread and running the code inside it instantly, you wanted to run the code after a delay? Well, RBLX Lua provides just that. The delay function creates a thread, then after x amount of time, runs the thread.

delay(3, function()
    print("world!") -- prints after 3 seconds
end)
print("Hello") -- prints instantly

Corountine Library

In vanilla Lua, creating a thread is harder (or in my opinion, easier!), but still works in the same fundamental way. You can create a thread by doing

local Thread = coroutine.create(function()
    print("Hello world!")
    wait(3)
    print("I like spaghetti!")
end)

and run it by doing

coroutine.resume(Thread) -- prints "Hello world!" and "I like spaghetti" without yielding the rest of the script.

You can also easily create a thread and run it by doing

local ThreadFunction = coroutine.wrap(function()
    print("Hello world!")
    wait(1)
    print("I am 1 second!")
end) -- creates a new function that starts the thread
ThreadFunction() -- runs the thread

"Suspending" threads

What if theres a loop inside the thread, and we want to stop when a condition is met, and only continue when we resume the thread? Well, you can call

local ThreadFunction = corountine.wrap(function()
    for i = 1, 10 do
        print(i .. " bottle of water on the wall!")
        coroutine.yield()
    end
end)
ThreadFunction() -- only prints "1 bottle of water on the wall!"
ThreadFunction() -- prints "2 bottle of water on the wall"