Working out a value: expressions

Syntax and values

An expression is code that produces a value, such as 2 + 3 or a question about a score. The order of its calculations can change the answer.

Reading the calculation rules

An operator is a calculation or question symbol, such as + or ==. Its operands are the values it uses. In 2 + 3, + is the operator and 2 and 3 are the operands. Unary means one operand; binary means two.

Precedence means priority when grouping code. Multiplication groups before addition: 2 + 3 * 4 gives 14, while (2 + 3) * 4 gives 20.

Associativity resolves a tie between operations with the same priority. “Left” means group from the left: 8 - 3 - 1 means (8 - 3) - 1. “Right” means group from the right, as with not not ready.

A primary expression is a basic value-producing piece, such as a literal, name, or parenthesized expression. A postfix comes after a value: [0] in players[0] selects an item. Chaining means adding several such steps, as in players[0].name.

Evaluation means working out the value. Priority determines the groups; evaluation order determines which parts are worked out first. The callee is the function being called. Short-circuiting explains when a part is deliberately skipped.

Precedence table

The table is ordered from lowest precedence to highest:

Level Operators or forms Associativity
1 or Left
2 and Left
3 ==, != Left
4 <, <=, >, >= Left
5 +, - Left
6 *, /, % Left
7 unary not, unary +, unary - Right
8 call (), index [], member . Left/chained

Examples:

1 + 2 * 3              # 7
not ready and enabled  # (not ready) and enabled
a or b and c           # a or (b and c)
player.items[0].name   # chained postfix operations

Use parentheses whenever grouping is clearer:

(1 + 2) * 3
not (ready and enabled)

Primary expressions

Primary expressions are:

  • number, text, Boolean, and none literals;
  • identifiers;
  • grouped expressions (expression);
  • list literals [a, b];
  • map literals {key: value}.

Postfix expressions

Calls, indexes, and members may be chained:

factory()(argument)
players[0].stats.score
matrix[row][column]

After ., the member must be a non-keyword identifier. Use indexing for a text
key that is a keyword or is not a valid identifier:

settings["if"]
settings["display-name"]

Evaluation order and short-circuiting

Evaluation is deterministic. A call evaluates its callee and then its arguments
from left to right. List elements evaluate left to right. Map entries evaluate
left to right, with each key before its value. An index evaluates its collection
before its index. Binary operands evaluate left to right, except that and and
or short-circuit:

  • false and right does not evaluate right;
  • true or right does not evaluate right.

Both evaluated operands of and and or must be Boolean.

Syntax and values · Built-ins · Programming guides