While is a pre-test loop; repeat until is a post-test loop.
A while statement is not guaranteed to execute the code, if the condition is not initially met, as it tests before running the code.
A repeat until statement is guaranteed to execute the code at least once, as it tests after running the code once, and if the condition is not met, then it keeps executing the code
You should use whichever one is relevant to what you want it to do.
Note that while requires the statement to be true to execute the code while repeat requires the statement to be false to execute the code [multiple times]
Bool = false
while Bool do
print("Hello")
end
-- Output:
Bool = true
repeat
print("Hello")
until Bool
-- Output: Hello
Really depends your specific situation and the logic you want to implement in your code. Both while and repeat until loops can be used to repeat a task until a certain condition is met
If you want to repeat a task while a certain condition is true, you can use a while loop. For example:
while num < 10 do
print("Number is less than 10")
num = num + 1
end
If you want to repeat a task until a certain condition is false, you can use a repeat until loop. For example:
repeat
print("Number is less than 10")
num = num + 1
until num >= 10
In terms of performance, both loops are equivalent and will not have any significant impact on your code’s efficiency, the main difference between them is the way the condition is checked and the order in which the task is performed
In a while loop, the condition is checked before the task is performed, while in a repeat until loop, the task is performed first, and then the condition is checked. This means that a while loop will only run the task if the condition is true, while a repeat until loop will always run the task at least once before checking the condition