Lua: Basic Mathematics

Although we've sort of touched on basic mathematical operators in previous tutorials, mostly the + operator which adds two numerical values together, I feel that having a whole tutorial dedicated to the basic mathematical operations could be helpful. As everything in Lua seems to be, these are extremely simple, but they are nevertheless very important.

The most basic mathematical operator is the one that we've already covered - the + operator. It adds the numerical value on the left of it to the numerical value to the right of it. We also found out that if you try to add a string to a number, the language will try to convert the string to a number for us, which is super sweet as user input usually comes in the form of a string. So we can accomplish very basic sums such as these:

1
2
3
print("5 add 3 is: " .. 5+3)
print("5 add 5 is: " .. 5+5)
print("3 add 2 is: " .. 3+2)

Note that the + operator, as well as all of the operators we will be covering in this tutorial, will also work fine with variables instead of constant number, and even with values inputted from the user (because, again, it should be able to convert the string value the user enters to a number). For example:

1
2
3
io.write("What number do you want to add 50 to?")
number = io.read()
print(number .. " add 50 is: " .. number+50)

Doing the same thing with multiple variables will also work fine:

1
2
3
4
5
6
7
io.write("Enter number one: ")
number = io.read()

io.write("\nEnter number two: ")
numbertwo = io.read()

print(number .. " add " .. numbertwo .. " is: " .. number+numbertwo)

Note that problems will occur if you try to perform arithmetic on a string that the interpreter cannot convert to a number:

1
2
number = "abcd"
print(number + 10) --Uh oh! You can't perform arithmetic on non-numerical strings!

This whole rule-set that we've now established for the + operator also applies for all the other basic mathematical operators that we are going to cover in this tutorial. Subtraction is achieved through using a dash or minus sign , -, multiplication is achieved through the asterisk symbol, *, and division is achieved through a forward slash, /. These should all be pretty self explanatory, so here is some code which you should understand that uses them:

1
2
3
4
5
6
7
8
9
10
io.write("Enter number one: ")
number = io.read()

io.write("\nEnter number two: ")
numbertwo = io.read()

print(number .. " add " .. numbertwo .. " is: " .. number+numbertwo)
print(number .. " minus " .. numbertwo .. " is: " .. number-numbertwo)
print(number .. " times " .. numbertwo .. " is: " .. number*numbertwo)
print(number .. " divided by " .. numbertwo .. " is: " .. number/numbertwo)