Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

How would you make a script loop? [closed]

Asked by
TofuBytes 500 Moderation Voter
10 years ago

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?

Locked by adark and evaera

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

2 answers

Log in to vote
2
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
10 years ago

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.)

1
Ah, I didn't know that. Thank you for the help, it works! :) TofuBytes 500 — 10y
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? blocco 185 — 10y
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. adark 5487 — 10y
Ad
Log in to vote
0
Answered by 10 years ago
while wait() do
print("Hi")
end

This will print "Hi" endlessly.