Lua: Operators

From Mario Fan Games Galaxy Wiki
Revision as of 22:32, 2 April 2010 by Xgoff (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Lua
Lua.gif
Basics
Intermediate
Advanced
XLua
Add to this template
 Standardwikimessagebox.png This article assumes the use of Lua 5.1.

Information may not be accurate or may need revision if you are using a different version.

Operators are special symbols or words that produce an effect on one or two operands and return some result; they are similar to functions but are much more efficient, having dedicated bytecodes.

The following table describes Lua's 18 operators, operand types, and the metamethod they trigger if applicable:

Left Operand Operator Right Operand Metamethod Priority Notes
T, N ^ T, N __pow 1
- T, N __unm 2
not Any 2 1
# T, S __len 2 2
T, N * T, N __mul 3
T, N / T, N __div 3
T, N % T, N __mod 3
T, N + T, N __add 4
T, N - T, N __sub 4
T, S .. T, S __concat 5
T, N, S < T, N, S __lt 6 6
T, N, S <= T, N, S __le, __lt 6 3, 6
T, N, S > T, N, S __lt 6 4, 6
T, N, S >= T, N, S __le, __lt 6 4, 6
Any == Any __eq 6 6, 7
Any ~= Any 6 5, 6, 7
Any and Any 7 8
Any or Any 8 9
  • T: Table/Full Userdata incorporating support for these operators
  • S: Strings
  • N: Numbers

Notes:

  1. Coerces operand into boolean and returns the opposite boolean value
  2. __len currently not implemented for tables
  3. Attempts __le; if not defined, attempts __lt assuming not (a < b)
  4. Lua reverses the operands and performs __lt or __le on them according to Note 3
  5. Use not in conjunction with __eq test to simulate not-equals metamethod
  6. Does not perform automatic coercion; operands must be same type if <, <=, >, or >=, otherwise an error is issued. Returns a boolean
  7. Behavior varies depending on type. Differing types always yield false. Numbers and strings compared as usual, different objects (tables, etc, by reference) of the same type are false unless overridden with __eq
  8. Returns second operand if first is true, else returns the first
  9. Returns first operand if first is true, else returns the second

Priority levels range from 1 for highest priority to 8 for lowest.

A highlighted operand cell indicates whether the operator is left- or right-associative; for instance: 2 + 3 + 4 == ((2 + 3) + 4), but 2 ^ 3 ^ 4 == (2 ^ (3 ^ 4)). This does not apply to unary operators, as all three of them have their sole operand to their right.