I have a game with a couple while true loops and I’ve been trying to figure out a certain problem and the only solution i’ve come up with is using a while true loop. What I wanted to know was is relying on these loops bad code practice? Since it’s constantly running? Just wanted to educate myself a bit appreciate y’all.
Avoid using them as much as possible, try to figure out alternative solutions that can do the same thing without wasting much of the resources. One of the approaches involve utilizing the while loops’ true purposes, you need to fill something in the condition in order for it to cease.
while (condition) do
-- your loop here
end
Using it in a function allows it to restart the loop.
function doSomething()
while (condition) do
-- your loop here
end
end
Or just dedicate it to events(or Signals if you’d like), which could be anything.
Usually if you want a loop to run a certain amount of times, you can do a for loop, for example:
Max = 10
Seconds = Max
for i = 1,10 do -- should fire 10 times
Wait(1) -- Fires Every second 10 times
Seconds -= 1
print(Seconds)
end
print("Times Up")
When you put in a loop, any code put below the Loop will not run until the loop has ended. You can try using a loop to do multiple things at once.
What not to do (unless you are breaking the loop):
while true do --this will never stop, unless you add an if statement.
wait()
print("lol")
end
print("stopped")
if you add an if statement, should look something like this:
Number = 10
while true do
Number -= 1
wait(1)
if Number <= 0 then
break -- stops the loop
end
end
You aren’t utilizing the while
loop correctly in this example.
Reconsider this instead:
timeValue = 10
while timeValue > 0 do
timeValue -= 1
wait(1)
end
Not exactly, <=
means less than or equal to, >
simply means greater than, plus, there is no break
so the loop wont stop.
Edit: I’m dumb, Both work either way, I’m not wrong, they are simply different methods
The loop I provided does indeed stop, it executes 10 times before actually stopping. It is not break that stops it, it is the condition that does it.
Did you forget to read my edit?
Just an additional note to the initial post: In a situation where you’re in a desperate use of while loops processing lots of code repeatedly, always halt and pause those loops whenever possible and then resume them when necessary.
Perhaps I should introduce to you this resource that I found very helpful working against the anti-pattern:
There is nothing fundamentally wrong with while loops, and if you ever work with a systems language that’s about all you’ll be using. They don’t cause performance problems when code needs to be repeated.
However, higher level languages like Lua benefit from event-driven programming, and that is what you should prefer. There’s no reason to make a loop that just waits for a condition to be true when there’s an event that does the same thing. The loop will run every frame or however often you specify and it will run a calculation each time. That costs a small amount of performance. An event just exists and does nothing until it’s called. This is clean, organized, and efficient. Events don’t sit in a cycle wasting resources until the condition is met.
If you need a while loop because an event doesn’t exist for what you need, then use a while loop. There’s no real harm in it. I use while loops all the time, sometimes it’s just the tool for the job.
That said, what @Operatik said is true. If you’ve got a while true do
with a single definitive break in it, just use while condition do
Usually i perfer to use:
repeat
wait(1)
Number -= 1
until Number == 0
I dont use while
often.
I find it pretty neat that repeat until
is a feature of LUA.
You should also know that repeat
and while
does perform one thing differently, that is when the condition has to be checked. If you want to not run the loop at least once, use while
. Otherwise you can use the guaranteed one iteration repeat
.
Just be aware that your code causes a slight issue here, if Number
for instance started at 0, and then resulted in -1. It would indefinitely go negative, because the code “missed the target”.
Yes, i know how loops work, im not stupid.
Would be helpful if you sepcified what “certain problem” means. In general, regardless of if it’s a while loop or not, you shouldn’t rely too heavily on loops. Try to make as much of your code as event-driven as possible. There’s not as many problems that require loops as the solution. Hard to tell what you actually need here if you don’t provide context on the problem.
As a generalised statement though, you probably should be conscious of how many while loops you’re executing but you most likely won’t reach the point where it’s noticeably impactful – just be mindful of what exactly the loop body has to execute.
Is this what you mean by using events instead of while loops? Sorry to resume this conversation after 4 months, I am just trying to get clarity on what people actually mean by using events rather than while loops. So, this post which I created and the method I am using, is it better off than while true do loops?
The Changed event is protected against infinite loops. It might take a while especially if you have a pause of some kind in there, but eventually you’ll get an error Maximum event re-entrancy depth exceeded
In this circumstance where your code is triggering itself every time it finishes, it is better to use a loop (vs what you mentioned in the original post on that thread you linked). That’s what loops are made for.
Event-based programming is more like what the solution to that thread was.
In this circumstance it doesn’t matter a huge amount which approach you take. I personally favor while loops. His answer would run the code every 60th frame regardless of lag, a while loop with a task.wait(60)
would run the code approximately every 60 seconds and the task.wait
would return the exact time it waited for so you could compensate for lag. You could still compensate for lag with his method too, it just wouldn’t be so straightforward. They both have their advantages and either might be more ‘correct’ depending on the circumstance and when your code needs to run.
Oh, alright. Thank you so much for clearing me on this. So in summary, in my case of a digital clock, I should be using a while true do
loop with a task.wait(n)
, right? And, creating an infinite looping system the way I did is a bad practice because it will eventually throw an error, correct? Also, for round systems and other timers, are while loops preferred or RunService.Heartbeat
? Anyways, thanks once again!
Edits: I’ve seen a few posts on the devforum about maximum event re-entrancy depth exceeded
, but in those scenarios the infinite loop is created without any cooldowns in between. Here I have given a wait of 15 seconds in the middle for a minute to complete. So will I still run into this error? You did mention that I will eventually arrive at that error but, we use .Changed
event many times in our Roblox games and values change multiple times. So will this error still occur if the server runs for long?
Repeat until is a while loop with a Break if-condition in it.
I dont recommend repying to year old topics, it does not help in the way you think it does.
And also:
This isnt really true, both repeat
and while
loops have the same condition check, however repeat
checks for a true
value, rather than a false
value as compared to a while
loop.
while i == 2 do -- repeats until i is not equal to 2
end
repeat
until i == 2 -- repeats until i is equal to 2
-- same concept, different ways of evaluating.
-- if I wanted them to work in the same way
while i == 2 do -- repeats until i is not equal to 2
end
repeat
until i ~= 2 -- repeats until i is not equal to 2
A for
loop is also a conditional loop in many other programming languages, for example: JavaScript.
for(var i = 0; i<10; i++){ // standard for loop
}
/*
This loop will increment until the condition is false
which in this case, it will break out if i is no longer
less than 10, where as the value will start at 0, and
incrememnt if the condition is false.
*/