Programming & Scripting Tutorials

Lua: Basic Mathematics



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

So most basic mathematical operator is the one that we've already covered – the '+' operator. It adds numerical values together (and if you try to add a string to a number, it'll try to convert the string to a number (as we found out in the previous tutorial)).
So we can accomplish very basic sums such as these:

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


The '+' operator will also work fine with variables (and even with values inputted from the user because it should be able to convert the string value the user enters, to a number). For example:

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


We can also use multiple variables if we so choose:

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:

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


This whole ruleset 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:

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)


This Lua tutorial was written by


Back to Lua

Advertisement: