Loop variants in Xojo
Recently a beginner asked about the differences between the loops and which too choose. Let's compare the loops by using them to count up from a start to an end value.
The first loop is the FOR loop. It counts a variable up from a start value to the end value. If the start value is bigger than the end value, the loop is skipped entirely. Let us show you the sample code:
You are not limited to double, but you can use any data type you like, e.g. a double. Here we step by 0.3 instead of the default 1, so we count up from 1.0 to 2.8. After 2.8 comes 3.1 which is too big, so the loop exists.
You can even define your own class for a numeric data type (or use one of our plugin classes) to do the count. Your class needs to implement Operator_Add for the step and Operator_Compare to the < comparison. The Operator_Convert is needed for an initial assignment. Here is a class wrapping an integer:
And then the loop looks just like before, but now uses MyType as numeric variable:
You can do the FOR loop with WHILE. The things translate part by part. The For i As Integer = First
becomes Var i As Integer = First
. The To Last
becomes While i <= Last
and the step part becomes the i = i + 1
. Yes, please never forgot to change the variable used for the loop, because otherwise you have an endless loop. Here is the test function to do the same as above FOR loop as a WHILE loop:
The DO loop does the comparison on the end of the loop. So we have to make the first comparison ourself and only enter the loop if the condition matches. If First is bigger than Last, we skip the loop. So we have an implementation of the FOR loop with DO LOOP:
Alternatively you can have the check on the beginning after the DO keyword. This makes it just like a WHILE loop, but with negated condition:
Without loops we can do the same with recursion. If another loop is needed, we let the function call itself. To make sure the check is done on the first call, we perform the check before we do anything else. Then we can run our statements and call the function to continue the loop:
You learnt something new? Let us know if you have questions for future blog posts.
See also: For each loops in detail