Not really an issue but a general question regarding scripting. When conditionally iterating, which of the below options is better.
Repeat Until
repeat
--code
until --condition
While Do
while --[[condition]] do
--code
end
Whilst thinking about this I considered that repeating until a condition is met will repeat once after the value which you are checking changes and you may have to compensate for this. However, overall which of the two methods is advised? Is one more, for example, more efficient than the other?
Mainly preference and what the situation needs; repeat until will perform the code at least once before checking if the condition is met, whereas while condition do will not run any code if the condition is initially false.
I don’t believe either is worse performance wise, but I may be wrong. If there is a difference it’s likely to be extremely small/negligible.
It ultimately doesn’t matter. They’re just opposites of each other. Use which ever one you want. Just be consistent.
And yeah that thing where the body of a repeat until executes at least once, unless you want that, use a while loop but other than that use whichever you want, and (be consistent [2])
I actually got here first but my internet went down so they beat me so hah i win
Both forms should be just as efficient, relative to the cost of the condition and the loop.
repeat until will run the loop, then the condition.
whereas,
while do will run the condition, and if true, then the loop.
In theory, the while do structure would be more performant because it allows for the chance that the loop portion isn’t run. The repeat until structure will always run both the loop and condition at least once regardless.
A good visualization is forcing yourself only to use while true do loops to create both structures:
-- the while loop
-- Notice that [[ code ]] has the chance of never being ran
while true do
if not --[[ condition ]] then
break
end
--[[ code ]]
end
-- the repeat loop
while true do
--[[ code ]]
if --[[ condition ]] then
break
end
end
Just because one loop is more or less expensive than the other does not mean you should be changing your code to fit the criterion specifically for its performance. I have seen myself use while loops countless times even though it follows the same behavior has the repeat loop:
--[[ code ]]
while --[[ condition derived from code ]] do
--[[ the same code ]]
end
And the same for using repeat loops for while loop behavior:
if not --[[ condition ]] then
repeat
--[[ code ]]
until --[[ the same condition ]]
end
This can lead to very messy code if you are not careful, and messy code is never a good thing!