Operators
305
Lua provides a variety of different built-in operators.
Arithmetic operators
Those are operators to do usual math:
a = 20
b = 5
print(a + b) -- Addition operator. Prints 25
print(a - b) -- Substraction operator. Prints 15
print(a * b) -- Multiplication operator. Prints 100
print(a / b) -- Division operator. Prints 4.0
print(a ^ b) -- Exponent operator. Prints 3200000.0
print(a % b) -- Modulus operator. Prints 0
Comparative operators
Those operators are usually used to define some sort of condition. They produce boolean values.
a = 20
b = 5
print(a == b) -- Checks if a equals to b. Prints false
print(a ~= b) -- Checks if a is not equal to b. Prints true
print(a > b) -- Checks if a is greater than b. Prints true
print(a >= b) -- Checks if a is greater or equal to b. Prints true
print(a < b) -- Checks if a is less than b. Prints false
print(a <= b) -- Checks if a is less or equal to b. Prints false
Logical operators
Logic operators are used to compose complex conditions. They operate on boolean values and produces also boolean values.
a = 20
b = 5
c = 10
d = 30
print(a < b and c < d) -- Logical "and" operator. Prints false
print(a < b or c < d) -- Logical "or" operator. Prints true
print(not a < b) -- Logical negation operator. Prints true
Other operators
a = 20
t = {1, 2, 3}
s1 = "Hello, "
s2 = "World!"
print(-a) -- Unary minus operator. Prints -20
print(#t) -- Table size operator. Prints 3
print(s1 .. s2) -- String concatenation operator. Prints Hello, World!
Rate this post:
Lesson 4
Lesson 6
Share this page:
Learning plan
The most simple Lua program and where you can run it
A very brief overview of Lua syntax and expressions
4. Data types
A list of data types and their descriptions which Lua operates on
5. Operators
A list of built-in operators in Lua
6. Control flow
A list of Lua statements which you use to organize control flow of a program
7. Functions
What kind of functions are there and how to write them
How to write tail recursion in Lua properly