Lua - Arithmetic Operators



Following table shows all the arithmetic operators supported by Lua language. Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
^ Exponent Operator takes the exponents A^2 will give 100
- Unary - operator acts as negation -A will give -10

Example - Arithmetic Operations

In this example, we're creating three variables a, b and result and using arithmatic operators, we've performed addition, subtraction, multiplication and division operations and printed the results −

main.lua

a = 21
b = 10
result = a + b
print("a + b = ", result )

result = a - b
print("a - b = ", result )

result = a * b
print("a * b = ", result )

result = a / b
print("a / b = ", result )

Output

When you execute the above program, it produces the following result −

a + b =    31
a - b =    11
a * b =    210
a / b =    2.1

Example - Modulus Operation

In this example, we're creating variables a,b,c and result and using arithmatic operator %, we've performed modulus operations between their values −

main.lua

a = 10
b = 20
c = 25
result = b % a
print("b % a = ", result )

result = c % a
print("b % a = ", result )

Output

When you execute the above program, it produces the following result −

b % a =    0
b % a =    5

Example - Exponent and Unary Operations

In this example, we're creating two variables a and b and using arithmatic operators. We've performed exponent and unary operations and printed the results −

main.lua

a = 10
b = 20
result = a^2
print("a^2 = ", result )

result = -b
print("-b = ", result )

Output

When you execute the above program, it produces the following result −

a^2 =    100
-b =   -20
lua_operators.htm
Advertisements