Language: Conditionals
Conditional statements allow your policy to behave differently depending on a condition.
Conditional 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.
If Statements
if
statements only execute their bodies if a condition is met.
The syntax of an if
statement is:
if condition { // ... this is executed if condition is true}
The condition
must result in a boolean, such as by calling a function
or evaluating a boolean expression. If
the condition
is true
, the body (within the {}
) is executed. Otherwise,
the body is skipped.
Examples:
// This would execute the bodyvalue = 12if value is 18 { print("condition met")}// Direct boolean values can be usedvalue = trueif value { print("condition met")}// This would not execute the body since the boolean expression will// result in undefined.value = {}if value["key"] > 12 { print("condition met")}
Else, Else If
An else
clause can be given to an if
statement to execute a body
in the case the condition is not met. By putting another if
statement
directly after the else
, multiple conditions can be tested for.
The syntax is:
if condition { // ...} else { // ...}if condition { // ...} else if other_condition { // ...} else { // ...}
Scoping
The body of an if
statement does not create a new
scope. Any variables assigned within the body
of an if statement will modify the scope that the if
statement itself
is in.
Example:
if true { a = 42}print(a) // 42
a = 18if true { a = 42}print(a) // 42
Case Statements
case
statements are a selection control mechanism that execute a clause based
on matching expressions. It is worth noting that the expression for case
is
optional. When no expression is provided, it defaults the expression to true
.
Additionally, the order of clauses is important, as they are evaluated from top
to bottom, executing the first match.
The syntax of a case statement is:
case expression { when clause_expression: // executed when clause_expression and expression are equal else: // executed if no clause matches expression}
When Clause
Any clause that has an expression for comparison must use the when
keyword.
It accepts a list of expressions, seperated by a ,
.
Example:
case x { when "foo", "bar": return true}
case { when x > 40: return true}
Else Clause
The else
keyword allows for capturing any expressions that have no matching
when
clause.
Example:
case x { when "foo", "bar": return true else: return false}