Condition placement
The repeat loop is essentially an inverted while loop. Yes it may seem weird explained like that, but it's not far off by any means. To understand this, first let's take a look at how the while loop works:
The while loop
The while loop will execute it's body of code only if it's condition is true, and only while it's condition remains true. Knowing this, we could take a look at this while loop example, and know that it won't do anything:
while false do
print("Running")
end
You should also notice that the while loop checks its condition before it runs it's code. This is another important difference between repeat and while. So now let's compare the two...
The repeat loop
As mentioned before, repeat is pretty much the opposite of while (though they're still both loops, and they will still both continue to run until their condition tells them otherwise). The only differences are outlined in their condition evaluation, and execution order.
Execution order
The order in which the while loop runs, is as follows: if condition == true then RunCode() Just like repeating an if statement, to check if it's condition is true before running it's code.
However, the order in which the repeat loop runs differs like such: RunCode() if condition == false then break They always run their code first, then check to see if the condition is false to break the loop.
Because of this inverted order, the syntax of the repeat loop differs as well. Instead of needing an "end" statement after the loop is created, it must be followed by "until". This is where the repeat loop's condition is evaluated after it's code has ran. The condition after it, simply tells the loop whether it should keep running or not.
Condition evaluation
Unlike how the while loop's condition must be true in order to keep running, the repeat loop's condition must be false or nil to continue running. Here's an example of an infinite repeat loop:
repeat
print("Hello world")
until false
The syntax of the loop above, also shows the execution order a bit more in detail. You can see the code is written first, because it's executed first. The condition is written last, because it's evaluated last. Here's an example:
repeat
print("Hello world")
until true
Creating a while loop with repeat?
So now knowing how repeat loops work, you could even imitate a while loop by using a repeat loop. Note back to where I said "Much like repeating an if statement, to check if it's condition is true before running it's code.". Which is exactly how we'd go about doing this. Simply have an if statement to check the condition before hand, and break the loop if it's evaluated as false or nil.
local Condition = false
repeat
if Condition then
print("Hello world")
else
break
end
until false
So, hope this helped. If you have any questions, just let me know and I'll get back to you as soon as possible.
2 comments
Thank you. Honestly, thank you very much.
Lovely.