Language: Loops
Loop statements allow you to execute a body of code for each element in a collection or for some fixed number of times.
Loop statements may only appear outside of rule expressions, such as in functions or in the global scope of a policy. This is because rules are only allowed to contain a single boolean expression.
For Statements
for
statements allow repeated execution of a block for each
element in a collection.
Example:
The syntax is for COLLECTION as value
. This will iterate over the
collection, assigning each element to value
. In the example above,
each element is assigned to num
. The body is executed for each element.
In the example above, the body adds num
to the count
variable. This
creates a basic sum of all values in the collection.
For a map, the assigned element is the key in the map. In the example
below, name
would be assigned map keys.
An alternate syntax is for COLLECTION as key, value
. This will assign
both the key and value to a variable. For a list, the key is the element
index. For a map, it is the key and value is assigned the element value.
Example:
Scoping
The body of a for
statement creates a new
scope. If a variable is assigned within
the body of a for statement that isn't assigned in a parent scope,
that variable will only exist for the duration of the body execution.
Example: