Operators & Expression Evaluation
PyLua provides modern operators—including native != inequality, 64-bit bitwise manipulation, floor division, and short-circuit evaluation—along with powerful metamethod customization.
1. Relational & Equality Operators
Unlike standard Lua which only provided ~=, PyLua natively supports the industry standard != operator:
| Operator | Operation | Example | Metamethod |
|---|---|---|---|
== |
Equal to | a == b |
__eq |
!= |
Not equal to (Modern) | a != b |
__eq (inverted) |
~= |
Not equal to (Traditional) | a ~= b |
__eq (inverted) |
< |
Less than | a < b |
__lt |
<= |
Less than or equal to | a <= b |
__le |
> |
Greater than | a > b |
__lt (swapped) |
>= |
Greater than or equal to | a >= b |
__le (swapped) |
2. Arithmetic Operators
PyLua operates on 64-bit IEEE 754 floats and 64-bit signed two's complement integers:
print(10 + 3) -- Addition: 13
print(10 - 3) -- Subtraction: 7
print(10 * 3) -- Multiplication: 30
print(10 / 3) -- Floating division: 3.3333333333333
print(10 // 3) -- Floor division: 3 (integer)
print(10 % 3) -- Modulo: 1
print(2 ^ 8) -- Exponentiation: 256.0
print(-15) -- Unary negation
3. 64-Bit Bitwise Operators
Bitwise operators treat operands as 64-bit signed integers:
| Operator | Operation | Example | Metamethod |
|---|---|---|---|
& |
Bitwise AND | flags & 0x0F |
__band |
| |
Bitwise OR | flags | 0x80 |
__bor |
~ (binary) |
Bitwise XOR | val ~ mask |
__bxor |
~ (unary) |
Bitwise NOT | ~mask |
__bnot |
<< |
Left shift | 1 << 4 (16) |
__shl |
>> |
Logical right shift | 16 >> 2 (4) |
__shr |
4. Logical Short-Circuit Operators: `and`, `or`, `not`
The logical operators and and or use short-circuit evaluation and return the operand value itself, rather than forcing a boolean:
-- Default value idiom with 'or':
displayName = customNickname or "Guest Player"
-- Safe dereference idiom with 'and':
playerSpeed = player and player.speed
-- Ternary expression idiom (condition and if_true or if_false):
status = isAlive and "Alive" or "Game Over"
5. String Concatenation (`..`) & Length (`#`)
The .. operator concatenates strings (and numbers, which are coerced to strings). The # operator computes the byte length of strings and the array portion length of tables:
greeting = "Score: " .. 100 .. " points"
print(greeting) -- "Score: 100 points"
print(#"Hello") -- String length: 5
items = { "A", "B", "C" }
print(#items) -- Table array length: 3
6. Operator Precedence Table
Listed from highest precedence (binds tightest) to lowest:
| Precedence | Operators | Associativity |
|---|---|---|
| 1 (Highest) | ^ |
Right-to-left |
| 2 | Unary not, #, -, ~ |
Right-to-left |
| 3 | *, /, //, % |
Left-to-right |
| 4 | +, - |
Left-to-right |
| 5 | .. |
Right-to-left |
| 6 | <<, >> |
Left-to-right |
| 7 | & |
Left-to-right |
| 8 | ~ (binary) |
Left-to-right |
| 9 | | |
Left-to-right |
| 10 | <, >, <=, >=, ~=, !=, == |
Left-to-right |
| 11 | and |
Left-to-right |
| 12 (Lowest) | or |
Left-to-right |