for ... in ... do ... end | for ... from ... to ... do ... end | while ... do ... end
Loops allow you to automatically execute a code block multiple numbers of times in succession. For example, apply the statements of a code block to each element of an array.
One of the most important loops you need to know about—it'll be very helpful when writing your scripts.
After for
, select the corresponding variable name for the item in the list that you want to change.
for
loop is structured as follows:Line 1: Not yet part of the loop but useful because it's easier to read: the records are stored in a variable.
Line 2: The loop starts with for
[it follows a label for a single element from the list to be traversed] in
[it follows the list] do
.
Line 3: statement of what should be done.
Line 4: end
terminates the loop (termination).
You'd like to assign all customers who have status 2
a new one, status 1
. First, select the customers with status 2
in the Customers (new) table. Then assign status 1
to each of these customers (customer
).
Result: All customers who have status 2
are assigned status 1
.
This loop is especially suitable when working with numeric values since instead of an array, a sequence of numbers will be iterated.
On each pass, 1
is added to the loop variable (increment = 1
). It starts with the value after from
(inclusive) and ends before the value after to
(exclusive).
Result: 60
The values of the array with the indices 0
, 1
and 2
are added. 10
+ 20
+ 30
= 60
.
Change the height of the increment with step
.
Result: 50
The values of the array with the indices 0
, 2
and 4
are added. 10
+ 30
+ 10
= 50
.
for i in range(0, 10)
is the equivalent of for i from 0 to 10
.
This loop is executed until the condition after while
is no longer true.
Declare a counter variable, for example, which is incremented on each loop pass until the condition is no longer true. The condition is correct (true
) as long as the variable is less than a specified value.
Result: 0 1 2 3 4 5 6 7 8 9
In most cases, for ... in ... do ... end
is the preferred choice.
If the condition is not set to false
on any of the passes, there's a risk of ending up in an infinite loop, causing Ninox to explode.