PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Jun 27 2019, 3:39 PM PST 2 min

Code threading is a method that allows two or more pieces of code to run at once. Threading becomes necessary when, for example, you want to run two while loops simultaneously:

while true do
	print("Loop 1")
	wait()
end

while true do
	print("Loop 2")
	wait()
end

This naive attempt fails because lines of code are run sequentially — this means the first loop never stops, so the second loop never gets executed.

Constructing a Thread

In Roblox, the spawn() function can be used to start a function in a new thread:

local function thread1()
	while true do 
		print("Loop 1") 
		wait()
	end
end

spawn(thread1)

At the moment, this thread method isn’t providing anything more than a non-threaded while loop, but it can be expanded upon to run two loops in parallel:

local function thread1()
	while true do
		print("Loop 1")
		wait()
	end
end

spawn(thread1)

-- Since 'thread1' is running in the background, the next loop will run
while true do
	print("Loop 2")
	wait()
end

For symmetry, the second loop can also be threaded:

local function thread1()
	while true do
		print("Loop 1")
		wait()
	end
end

local function thread2()
	while true do
		print("Loop 2")
		wait()
	end
end

spawn(thread1)
spawn(thread2)
Threading Considerations
  • Having many threads will eventually cause lag in a game, so it's best to keep thread count to a minimum by optimizing code and combining all functionality that can be mixed.
  • Just like functions, threads take on the environment of the parent context where they were created. So, any existing variables of its parent stack (local or global) will fall into the new thread's environment as well.

Tags:
  • lua
  • threading
  • thread