What is a Loop?
A loop is a chunk of code that is executed many times over. There are three types of loops, for, while, and repeat. Each one loops a block of code, but in different ways. You will see the differences between each of the loops later on. The reason why one would use a loop is that loops are great ways to not repeat the same code over and over. Let's dive in!
The while loop will evaluate the condition to see if it is true or false. If it is false, the loop will end. If it is true, the body of the loop after the 'do' statement will be executed, and the true/false condition will be reevaluated afterward.
As you can see in the above script, as long as i is less than 10, it will print the statement that i < 10. Once i has been incremented to a value equal to 10 (namely, 10), the while loop will end, and the final line will print that i=10.
The for loop is a way of running a command or set of commands a set number of times. The basic syntax is as following:
for iterator_variable = start value, end value, increment do
However, there is also a more complicated style of the for loop called the Generic For Loop, but for now we will just discuss the basics.
Keep in mind that as long as the iterator is between the start and end values, the code following the 'do' statement and before the 'end' will be executed.
For example, if you know you want to print "Hello Mom!" ten times, then you can use the for loop.
In the for loop, you see two numbers: 1, which is the starting value, and 10, which is the ending value. The loop will run from 1 to 10, and print "Hello Mom!" once per each number between 1 and 10 -- 10 times.
Lua will assume you are going to be adding positive numbers. If you want to get fancy, such as subtracting numbers, or adding decimals, you have to specify this as follows:
Notice that we have specified that we want to count downwards from 10 to 1, and we are subtracting 1 number every time.
Another example, but with decimals:
This will count upwards from 1 to 10 by halves.
A repeat ... until statement will repeat until a certain condition is met. The body is executed at least once, because the test is performed after the body (i.e., "the process is preceding the decision"). Repeat
This will print i < 10 until i has reached the value of 10, at which point it will print that i = 10.
If you have a while, a for, or a repeat loop that otherwise won't end, you can program it to end with the break command, so you can continue with the next part of code:
These loops only run once because of the break command, and print "Hi mom" once.
Notice in these three loops, something is wrong -- the loops would either take too long to end, or are neverending. We have to force them to end with break.