Skip to content

Operators

Rohan Singh edited this page Aug 10, 2021 · 30 revisions

The following operators are available, in order of precedence:

Category Operators
Postfix x.y, x[y], x(y), x++, x--, x[y:z:w]
Prefix -x, !x, ++x, --x, ~x, ...x, Unary UDO
Multiplication *, /, %, **
Addition +, -
BitShift <<, >>
BitAnd &
BitXor ^
BitOr |
Relational >, >=, <, <=, in, !in, Infix UDO
Equality ==, !=
Conditional And &&
Conditional Or ||
Ternary ?:
Assign =, +=, -=, *=, /=, %=, **=, &=, |=, ^=, <<=, >>=, |>

Indexing

Indexing is used to access a value contained in another value or its prototype. Indexing an array value with a number will access the value at the given index, negative indices will count from the last value.

Equality

These are the rules the equality operators (==, !=) follow:

  1. object will use the __eq metamethod to compare if defined.
  2. Values of different types will never be equal.
  3. number and string types of the same value will always be equal.
  4. object, array, and function types will only be equal if they refer to the same instance, not value.
  5. true, false, null, and undefined are only equal with themselves.

Relational

The relational operators (>, >=, <, <=) can only be used on number and string values. When used on string values the result allows you to determine sort order.

The __eq and __gt metamethods allow the relational operators to be used on object values.

Conditional And/Or

The conditional and/or operators (&&, ||) test if [[values evaluate to true|Conditionals#evaluation]]. The result of the operation will be the last evaluated value, which doesn't need to be true or false.

&& requires both values to evaluate to true while || only needs one value to evaluate to true.

Both operators support short circuiting. This means the right side of && will not be evaluated if the left side evaluates to false, or the right side of || will not be evaluated if the left side evaluates to true.

This behavior can used in many different ways, like providing default values:

fun square(num) {
    num = num || 100;
    return num * num;
}

var a = square(10); // 100
var b = square();   // 10000

Assignment Operators

The left-hand side of an assignment operator must be one of the following: a variable name, an x.y expression, or an x[y] expression. The right-hand side must contain a value which is to be stored in the location given to the left.

Combination assignment operators are provided for most operations. These operators modify the existing value instead of overwriting it. For example, x = x + 5 could be written as x += 5.