Arithmetics
Questions we will be answering:
- What is it?
- Why is it useful?
- How do I use it?
Expected knowledge:
What is arithmetics?
Arithmetics, for what we will be looking at here at least, are the main “operators” in maths - addition, subraction, multiplication and division. We’ll look at how to perform these actions in our scripts with numbers and variables.
Why is arithmetic useful?
It’s usefull for, well, really anything that involves maths. Whether that’s a simple number + number or something more complex, arithmetics will be used. It’s another thing essential to know for programming, and luckily isn’t too difficult to understand.
How do I use arithmetics?
The way arithmetics is used in programming is the same way as you would use it in maths - write out the first number, then what operator you are using (+, -, *, /) and the second number. For example, if I wanted to add
5
and3
together I would write out:
5 + 3
That line of code would be the same as just writing out
8
, because5 + 3 = 8
. Considering that the code5 + 3
is equal to the code8
, we can do things like printing out the value or storing the value in a variable:
print(5 + 3)
local sum = 5 + 3
What are the operators?
+
= Add
-
= Subtract
*
= Multiply
/
= Divide
Shortcuts
This isn’t absolutely necessary to know, though it is useful:
If you want to do something to an already existing number, i.e.
add 3
, you would want to do:
local number = 5
number = number + 3
Which would mean the variable
number
= the value ofnumber
plus 3 (equals 8). However, we can shorten this to just:
local number = 5
number += 3
It does the exact same thing, just a little shorter. This also works for any other operator.
Now that you know what arithmetics is, test your knowledge on these questions:
Question 1 (Easy)
How would I subtract 6
from 19
and print
out the answer?
Hint: Put the operator in between the two numbers
Answer:
print(19 - 6)
Question 2 (Medium)
What is the shortest way of adding 4
to a variable with a value of 9
?
Hint: Make sure you’ve read the “Shortcuts” part of this tutorial.
Answer:
local number = 9
number += 4
Question 3 (Hard)
How do I check if two numbers added together create 9
, and if they do print: “number1 + number2 = 9!”
Hint:
Here, we have to use something called “if statements” - our next topic. The way they’re used is by saying:
if (something) then
code here
end
Answer:
local number1 = 5
local number2 = 4
if number1 + number2 == 9 then
print(number1.. " + " ..number2.. " = 9")
end
P.S. I’m going to try to upload these tutorials more!