Skip to main content

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 andor, and not. These operators consider both false and nil as “false” and anything else as “true.”

OperatorDescription
andReturns true only when both operands are true
orReturns true when either operand is true
notReturns 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:

  1. For Example 1, the conditional test in the if...then will return false and the print() function will not be executed.
  2. For Example 2, the conditional test in the if...then will return true and the print() function will be executed. “Example 2 is true” will be printed to the log console.
  3. For Example 3, the conditional test in the if...then will return true and the print() function will be executed. “Example 3 is true” will be printed to the log console.

Arithmetic operators

Basic arithmetic operators are supported, including:

OperatorOperation
+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):

OperatorDescription
==Equal to
~=Not equal to
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to

Other operators

OperatorDescription
..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:

  1. A table called a is declared and initialized to contain nothing with empty {}.
  2. Indexes 1 to 5 of a are each assigned string values.
  3. The print() function is called, passing it #a which will return the length of table a, which equals 5.