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 |
|
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 |
|
Doing the same thing with multiple variables will also work fine:
1 2 3 4 5 6 7 |
|
Note that problems will occur if you try to perform arithmetic on a string that the interpreter cannot convert to a number:
1 2 |
|
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 |
|