Arithmetic Operators


Basics

Let's first take a look at the basics, addition, subtraction, multiplication, and division. These work as one would expect:

local x = 2
local y = 3

print(x + y) -- 5
print(x - y) -- -1
print(x * y) -- 6
print(x / y) -- 0.66666666666667

Negation

Whereas almost all languages allow a value to be negated by multiplying it by -1 to negative it, Lua additionally allows a value to be negated by simply prefixing it with -.

local x = 2
local y = 3

print(-x) -- -2
print(-y) -- -3
print(x + -y) -- -1

Note that negation occurs independently of other operators, as shown in the last case. We will learn more about this in a moment when we discuss precedence.

Exponentiation

Lua supports exponentiation with the ^ operator:

local x = 2
local y = 3

print(x ^ y) -- 8.0
print(y ^ -x) -- 0.11111111111111

Modulus

Like many programming languages modular arithmetic in Lua uses the % operator. While the topic of modular arithmetic is well outside the scope of learning about Lua, this is a useful but often misunderstood function, so let's give it a quick review.

To calculate a % b, one first finds the largest integer k such that multiplying k by b is less than a, then the result is the difference or remainder, a - kb.

local x = 2
local y = 3

print(x % y) -- 2
print(y % x) -- 1

In the first example y is greater than x, so the remainder is simply x. In the second example the largest integer k is 1, so that the remainder is 3-2=1.

Bitwise

Lua also supports the basic bitwise operations. While bitwise operations are very important in computing, they are used in a fairly narrow range of applications so we won't spend too much time on them other than to show which operations are supported and a simple example of how they work:

local x = 2
local y = 3

print(x & y) -- 2
print(x | y) -- 3
print(x ~ y) -- 1

You can learn more about bitwise operations here.