Operators
Prerequisites: Numbers and math, Strings
Comparison
print(5 == 5)
print(5 ~= 3)
print(10 > 9)
print(3 <= 3)
print("apple" < "banana")
print("10" == 10)
print({} == {})
true
true
true
true
true
false
false
- Not equal is
~=, not!=. ==never converts types: the string"10"isn't equal to the number10.- Tables are compared by identity: two separate empty tables are different objects.
Logical
and, or, and not (words, not symbols):
local age, hasTicket = 20, true
print(age >= 18 and hasTicket)
print(age < 13 or age > 65)
print(not hasTicket)
print(not nil)
true
false
false
true
Other operators
| Operator | Meaning |
|---|---|
.. |
concatenate strings |
# |
length of a string or array |
&, |, ~, <<, >> |
bitwise and, or, xor, shifts (integers, Lua 5.3+) |
~x |
bitwise not |
print(#"hello")
print(#{10, 20, 30})
print(6 & 3, 6 | 3, 6 ~ 3, 1 << 4)
5
3
2 7 5 16
Precedence
From highest to lowest: ^, unary (not, #, -, ~), * / // %,
+ -, .., shifts, &, ~, |, comparisons, and, or. When in
doubt, use parentheses. Note that ^ binds tighter than unary minus:
-2 ^ 2 is -4.0.