Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

1 script and 2 while loops running at once?

while wait(1)do
print'1'
end
while wait(2)do
print'2'
end

It never prints 2. Is it possible to make the both while loops start running at once without putting them into two different scripts?

1 comment

0

From what I know, you can't run two separate loops at the same time unless one was inside a function that was fired by an event while the same script was looping something else.

1 answer

✓ Accepted answer

Spawn

First of all: don't use coroutine if you're only using it to make "threads" that make code "happen at the same time".

A good test: if you're not meaningfully using coroutine.yield, don't use coroutine at all.

Instead, use spawn and delay to create "background threads"

spawn(function()
	-- "in the background" loop
	while true do
		print("background loop")
		wait()
	end
end)

while true do
	print("foreground loop")
	wait()
end

Avoid threads

Second of all: it is usually a mistake to use spawn / have multiple threads. Your code can really quickly become confusing and complicated.

By interleaving work, you can do multiple things at the same time, in a very controlled way.

e.g., why wouldn't you just use this instead?

while true do
	print("background loop")
	print("foreground loop")
	wait()
end

See these threads for more detailed examples:

This discussion is preserved as it was. New answers, comments, and votes are closed.