Search
⌃K
Links

Repeat conditional statements with loops

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.

for ... in ... do ... end

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.

The 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).

Example

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).
1
let customers := select 'Customers (new)' where Status = 2;
2
for customer in customers do
3
customer.Status := 1;
4
end
Result: All customers who have status 2 are assigned status 1.

for ... from ... to ... do ... end

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).

Example

1
let array := [10, 20, 30, 20, 10];
2
let result := 0;
3
for i from 0 to 3 do
4
result := result + item(array, i)
5
end;
6
result
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.

Example

1
let array := [10, 20, 30, 20, 10];
2
let result := 0;
3
for i from 0 to 5 step 2 do
4
result := result + item(array, i)
5
end;
6
result
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.

while ... do ... end

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.
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.
😉
​

Example

1
let i := 0;
2
let result := "";
3
while i < 10 do
4
result := result + " " + i;
5
i := i + 1
6
end;
7
result
Result: 0 1 2 3 4 5 6 7 8 9
In most cases, for ... in ... do ... end is the preferred choice.