Operators
An operator is a symbol used to perform an operation or conditional check.
Logical operators
Logical operators can be used to perform boolean logic. The logical operators for conditional statements are and
, or
, and not
. These operators consider both false
and nil
as “false” and anything else as “true.”
Operator | Description |
---|---|
and | Returns true only when both operands are true |
or | Returns true when either operand is true |
not | Returns the opposite of the operand - i.e. true when the operand is false and false when the operand is true |
a = 3
b = 4
-- Example 1
if a == 1 and b == 4 then
print('Example 1 is true')
end
-- Example 2
if a == 1 or b == 4 then
print('Example 2 is true')
end
-- Example 3
if not a == 1 then
print('Example 3 is true')
end
When the above program runs:
- For Example 1, the conditional test in the
if...then
will returnfalse
and theprint()
function will not be executed. - For Example 2, the conditional test in the
if...then
will returntrue
and theprint()
function will be executed. “Example 2 is true” will be printed to the log console. - For Example 3, the conditional test in the
if...then
will returntrue
and theprint()
function will be executed. “Example 3 is true” will be printed to the log console.
Arithmetic operators
Basic arithmetic operators are supported, including:
Operator | Operation |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
^ | Exponentiation |
% | Modulus |
- | Unary negation (putting this operator before a number will make it negative.) |
Conditional operators
Conditional operators compare two parameters and return a boolean (true
or false
):
Operator | Description |
---|---|
== | Equal to |
~= | Not equal to |
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
Other operators
Operator | Description |
---|---|
.. | string concatenation |
# | length of table (highest number index of a table) |
local count = 12
print('There are ' .. count .. ' months in one year')
The above print()
function will print “There are 12 months in one year” to the log console.
a = {}
a[1] = 'player1'
a[2] = 'player2'
a[3] = 'player3'
a[4] = 'player4'
a[5] = 'player5'
print(#a)
When the above program runs: