Numbers: Integers, Floats and Division

Lua numbers come in two kinds. Integers are whole numbers, like 3. Floats are numbers with a decimal point, like 3.0 or 3.5. You can ask Lua which kind a number is with math.type:

print(3)
print(3.0)
print(math.type(3), math.type(3.0))

Output:

3
3.0
integer	float

3 and 3.0 have the same value, but a float always prints with its decimal point. This matters most when you divide.

Division

The / operator always gives a float, even when the numbers divide evenly:

print(7 / 2)
print(10 / 5)

Output:

3.5
2.0

10 / 5 prints 2.0, not 2. When you want a whole-number answer, use //, floor division. It divides and then rounds the result down to a whole number. The % operator gives the remainder, the part that is left over:

print(7 // 2)
print(7 % 2)

Output:

3
1

2 fits into 7 three whole times, with 1 left over. The remainder is useful more often than you might expect. For example, n % 2 is 0 for even numbers and 1 for odd numbers.

Other operators

+, - and * work as you would expect, and parentheses group parts of a calculation. ^ raises a number to a power. Like /, it always gives a float:

print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ^ 10)

Output:

14
20
1024.0

Some languages let you write x += 1 to add 1 to a variable. Lua does not:

local x = 5
x += 1

Output:

/usr/bin/lua5.4: main.lua:2: syntax error near '+'

In Lua you write x = x + 1 instead.

In the exercise, fill in the right operator for each of the three divisions.