Numbers
print can print numbers too. Numbers are written without quotes, and Lua can calculate with them. When you put a calculation in the parentheses, Lua works it out first and prints the result:
print(42)
print(7 + 5)
print(20 - 9)
print(3 * 4)
print(5 - 8)This prints:
42
12
11
12
-3For the basic arithmetic, Lua uses these operators (symbols for operations):
+addition-subtraction*multiplication (a star, because there is no × on the keyboard)/division
A calculation in quotes is a text, and a text is printed exactly as it is written: print("7 + 5") prints 7 + 5.
As in math, multiplication and division come before addition and subtraction, and operations of the same level are done from left to right. If you want a different order, use parentheses:
print(2 + 3 * 4)
print((2 + 3) * 4)This prints:
14
20In the first line, Lua multiplies 3 * 4 first, which is 12, and then adds 2. In the second line, the parentheses make it add 2 + 3 first, and only then multiply the 5 by 4.
Division has one surprise:
print(7 / 2)
print(10 / 2)This prints:
3.5
5.0Division with / always gives a decimal number, even when the result is whole, so 10 / 2 prints 5.0, not 5. It's the same value, just a different kind of number. Lua has two kinds of numbers, whole and decimal, and you'll learn all about them in the next lesson.
Decimal numbers are written with a dot, 2.5, never with a comma (you'll see why in the next exercise). Write big numbers without spaces or commas, too: 1250, not 1 250 or 1,250. The spaces around operators, on the other hand, don't change anything; they just make the code easier to read. And multiply with *, not with the letter x: print(3 x 4) ends with an error.
Instructions
Emma's hens laid 7 eggs on Monday, 9 on Tuesday and 8 on Wednesday. Run the program: its second line prints the calculation as a text. Remove the quotes around it, so that Lua adds up the eggs, and the program prints:
Eggs from Monday to Wednesday:
24Emma sells eggs in boxes of 6. Below, print the heading Full boxes:, and on the next line, let Lua work out how many boxes the eggs fill: the sum of the eggs, divided by 6. Use parentheses, so that Lua adds before it divides. Division gives a decimal number, so the program prints:
Eggs from Monday to Wednesday:
24
Full boxes:
4.0At the market, Emma sells 3 boxes for 12 coins each, and she pays 5 coins for her place at the market. Print the heading Coins from the market:, and below it, let Lua calculate what she earns: the price of the 3 boxes, minus 5. This time, you don't need parentheses, because multiplication comes first anyway. The program then prints:
Eggs from Monday to Wednesday:
24
Full boxes:
4.0
Coins from the market:
31Start programming for free
3/7