» Language: Conditionals

Conditional statements allow your policy to behave differently depending on a condition by using if statements.

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 body
value = 12
if value is 18 {
    print("condition met")
}

// Direct boolean values can be used
value = true
if 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 = 18
if true {
    a = 42
}

print(a) // 42