How do use use spawn()?

spawn(f) executes f in a new “thread”, without yielding the current thread. Think of a thread as a traffic lane of instructions that need to be executed. When we create a new thread/traffic lane, instructions/vehicles can flow through it without being affected by instructions/vehicles in other threads/traffic lanes. If thread 1 has a road block (for example a wait(x)), thread 2, 3, etc. can continue as normal:

I do not recommend using spawn, as it has a built-in wait() at the beginning. Instead, use the coroutine library:

-- create a new coroutine and resume it with 2 passed to n
coroutine.wrap(function(n)
    wait(n)
    print("executed 2nd")
end)(2)

print("executed 1st")

--> executed 1st
--> executed 2nd

Edit: Nowadays you should use task.spawn!

83 Likes