Sentinel
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:
// A basic sum
count = 0
for [1, 2, 3] as num {
count += num
}
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.
list = []
for { "a": 1, "b": 2 } as name {
append(list, name)
}
print(list) // ["a" "b"]
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:
count = 0
for { "a": 1, "b": 2 } as name, num {
count += num
}
print(count) // 3
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:
for list as value {
a = 42
}
print(a) // undefined
a = 18
for list as value {
a = 42
}
print(a) // 18