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
The break
must be in the loop, also shouldn't have parenthesis on it
The loop will never end because it's infinite and will never run lines 4-5
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')
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!