// Value equality for primitivesprint(42==42);// trueprint("hello"=="hello");// true// Reference equality for tableslett1={1,2,3};lett2={1,2,3};lett3=t1;print(t1==t2);// false (different tables)print(t1==t3);// true (same reference)
Logical Operators
Operator
Description
Short-circuits
&&
Logical AND
Yes
||
Logical OR
Yes
!
Logical NOT
N/A
Short-Circuit Evaluation
Logical operators short-circuit: they don’t evaluate the right operand if the result is determined by the left operand.
// AND: if left is false, right is not evaluatedletx=false&&expensive_function();// expensive_function() not called// OR: if left is true, right is not evaluatedlety=true||expensive_function();// expensive_function() not called// Useful for safe accessletsafe=(obj!=nil)&&(obj["value"]>0);
Only false and nil are falsy. Everything else is truthy:
if(0){print("0 is truthy");}// Printsif(""){print("Empty string is truthy");}// Printsif({}){print("Empty table is truthy");}// Printsif(false){print("Won't print");}if(nil){print("Won't print");}
// Without parenthesesletx=2+3*4;// 14 (not 20)lety=10-5-2;// 3 (left-to-right)letz=2**3**2;// 512 (right-to-left: 2^(3^2))// With parentheses for clarityleta=(2+3)*4;// 20letb=10-(5-2);// 7letc=(2**3)**2;// 64
Compound Assignment Operators
Operator
Equivalent
x += y
x = x + y
x -= y
x = x - y
x *= y
x = x * y
x /= y
x = x / y
x %= y
x = x % y
x &= y
x = x & y
x |= y
x = x | y
x ^= y
x = x ^ y
x <<= y
x = x << y
x >>= y
x = x >> y
Examples
letx=10;x+=5;// x = 15x*=2;// x = 30x/=3;// x = 10x%=7;// x = 3
Increment/Decrement Operators
Operator
Description
x++
Post-increment: use then add
++x
Pre-increment: add then use
x--
Post-decrement: use then subtract
--x
Pre-decrement: subtract then use
Examples
leti=5;// Post-incrementleta=i++;// a = 5, i = 6// Pre-incrementletb=++i;// b = 7, i = 7// Post-decrementletc=i--;// c = 7, i = 6// Pre-decrementletd=--i;// d = 5, i = 5
In Loops
for(leti=0;i<10;i++){// i++ increments after each iterationprint(i);}for(leti=0;i<10;++i){// ++i also works, same effect in for loopprint(i);}
Operator Overloading
Tables can define custom operator behavior using metamethods. See Tables - Metatables for details.