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

How would you make a script loop?

I'm sort of lost on the idea of how to make for example a game or minigame script that will continue to loop itself. I've been trying to figure out loops and I don't think while true do is the most efficient way to loop my game script. Any ideas on how I can loop my script better?

2 answers

✓ Accepted answer

If you want an unconditional infinite loop, while true do .. end is actually the way to go.

Inside, you can use the wait method of Events to avoid having to utilize busy waits, for increased efficiency:

while true do
	script.Parent.Touched:wait() --lowercase 'w' ":Wait()" will error
	print("script.Parent was Touched!")
end

If you ever run into a case of having to use some kind of busy wait:

while not script:FindFirstChild("LocalManager") do
	wait()
end

Try and script to avoid that:

while not script:FindFirstChild("LocalManager") do
	script.ChildAdded:wait()
end

And if you can't figure out how to do that, by all means ask here.

(In this case, you could just use WaitForChild, but this is the best example of this I could think of right now. I'd actually be surprised if this wasn't the code for WaitForChild internally.)

3 comments

1

Ah, I didn't know that. Thank you for the help, it works! :)

1

Unconditional is a misnomer. There's still a conditional expression here, it's just that it always evaluates to true. So I guess it's an unconditional conditional loop?

0

Fair point. "while true do" is an uncoditional infinite loop, because the condition is 'true' regardless of state. "while someVar do" would then be a conditional infinite loop, so long as someVar is 'true' or truthy, which cannot be garuanteed.

while wait() do
print("Hi")
end

This will print "Hi" endlessly.

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