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

Break() function not properly breaking loops?

Asked by 5 years ago

Hello there, (omg what is that title)

For the past couple of months I wanted to make a while wait() do loop that would stop itself using the break() function.

I obviously know that if I do this script:

while wait(0.5) do
print("hello")
end
wait(5)
break()

It wouldn't work, so I want to learn how to use that function CORRECTLY, and learn how to break loops after a certain amount of time.

Help would be appreciated!

-Fragmentation123

4
`break` is a keyword, not a function. It is used similarly to `return`. Link150 1355 — 5y

2 answers

Log in to vote
3
Answered by
Rare_tendo 3000 Moderation Voter Community Moderator
5 years ago
Edited 5 years ago
  1. The break must be in the loop, also shouldn't have parenthesis on it

  2. The loop will never end because it's infinite and will never run lines 4-5

  3. Here's a solution:

local t = tick()

while true do
     if tick()-t >= 5 then
          break
     end
     print('henlo')
     wait(0.5)
end

print('broke out of while loop')
0
Thanks pal! Fragmentation123 226 — 5y
0
no problem mate sonysunny 36 — 5y
Ad
Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

While the other answer is pretty decent I would like to post an answer explaining the issue with while wait() do loops. The other answer addressed your break issue so I will only explain the issue with while wait() do. A lot of people are encouraging the use of wait() as a condition so that you don't forget to wait in your loop. This is a bad reason and a great explanation as to why can be found here. The main issue I would like to address though is that the while wait() do idiom has caused us to forget the purpose of a condition. The conditional of a while loop is there for us to use, not just to put something in to make it run. By using wait() as your condition you are forgetting what the condition is for. I can more easily do fix your break issue by not needing a break at all. Example:

while tick()-t < 5 do
    print("hello")
    wait(.5) -- because there is an ending condition in the while loop you may not need a wait but if it does not terminate quick enough it will freeze the game.
end
print("finished loop")

Here without needing an extra if statement I managed to do what you wanted. This is the power of the condition in a while loop. Stop using wait() and actually think about what the condition of the while loop is for. I hope this helps and have a great day scripting!

0
game:GetService("RunService").RenderStepped:wait() Fragmentation123 226 — 5y

Answer this question