Conditional statement

Conditional statement

Conditional statement

Function

conditional statement is used to execute different codes according to different conditions. if in BT is also an expression: the value of the entire if is returned by the last statement in the actual execution branch; empty is returned when there is no matching branch.

Syntax

if

Write the condition after if. The first block of code is executed when the condition is true.

else

else represents the back-up branch executed when none of the previous conditions are true.

elseif and else if

elseif are used to continuously judge multiple conditions; else if can also be written as a nested condition.

The ternary conditional expression

can use condition ? true_value : false_value to simply choose one of the two, which is suitable for short expressions but not suitable for writing complex business blocks.

match expression

Function

match is used to compare the values of an expression in order and return the result of the first hit branch. It is suitable for replacing consecutive if / elseif / else judgments.

Syntax

Parameters

  • expr: The expression to be matched will only be evaluated once.
  • pattern: Branch mode expression that compares for equality with the target value in order from top to bottom.
  • _: Default branch, returns its expression value when none of the previous ones match.

Return Value

match is an expression. After hitting a branch, the value of the expression on the right side of the branch => is returned; when the {} code block is written on the right side of the branch, the value of the last statement of the code block is returned; when there is no match and there is no _ default branch, empty is returned.

Code Examples

Notes

  • match matches in the order in which branches are written. After a hit, subsequent branches will not be checked.
  • _ is the default branch, usually placed at the end; if placed in the front, subsequent branches will not be executed.
- The right side of the branch can be an expression or a {} code block; the value of the code block is determined by the last statement.
  • return will exit the current function or script directly, not just return the current match branch; if you just want to give the value to match, please use the value as the last statement of the code block.

Truth Rules

The condition will be judged according to BT's truth rules. Common false values include false, null, empty, 0, empty string, empty array, and empty object; other values are usually treated as true.