Summary
In this lesson, you learned that:
- A variable is a name for a value:
local coins = 120.=means “store”, not “equals”. You writelocalonce, when you create the variable; without it, Lua creates a global variable. In this course, every variable is local. - Names contain the letters a to z, digits and
_, don't start with a digit, and can't be keywords. Uppercase and lowercase letters matter. This course writes them in camelCase:seedPrice. - You change a variable by storing a new value in it, often calculated from the old one:
coins = coins + 5. Standard Lua has no+=or++. - Numbers are integers (
5) or floats (5.0), and floats are written with a decimal point./and^always give a float,//divides and rounds down, and%gives the remainder.math.typetells you which kind a number is. math.floorandmath.ceilround down and up and return integers;math.floor(x + 0.5)rounds to the nearest whole number.math.max,math.minandmath.absreturn the largest value, the smallest value and the absolute value.- Texts (strings) go in
"…"or'…'.\",\nand\tare a quote, a new line and a tab...joins texts without adding spaces, and#gives the length in bytes. nilmeans no value. A variable without a value, and a name with a typo, givenil, and joining or calculating with it is an error.(local 'x')in the message means a variable without a value,(global 'x')usually a typo.trueandfalseare booleans.typereturns the type of a value as a text:"number","string","boolean","nil".tonumberturns a text into a number, or returnsnilif the text isn't one;tostringturns any value into a text. Lua converts some texts to numbers by itself, but don't rely on it.string.formatbuilds a text from a template:%dfor a whole number,%.2ffor two decimal places,%sfor any value,%%for a percent sign.
In the next lesson, on conditions, your programs will learn to make decisions: to do one thing or another, depending on the values of variables.
Instructions
Before you go on, try it all out on Emma's evening report. Calculate how many full boxes Emma can fill with her eggs and how many eggs are left over, and print it like this:
Boxes: 4, eggs left: 3Emma sells the full boxes for boxPrice each. Add the money to coins, and print coins with string.format and two decimal places:
Boxes: 4, eggs left: 3
Coins: 58.00Grandpa Joe pays back the coins he owed Emma. The amount is in his note, joeNote, which is a text. Convert it with tonumber, add it to coins, and print coins with ... You'll see .0 at the end: coins became a float when you added the money for the boxes, because boxPrice is a float.
Boxes: 4, eggs left: 3
Coins: 58.00
Coins: 73.0Emma writes only whole coins in her notebook. Print coins once more, with string.format and %d:
Boxes: 4, eggs left: 3
Coins: 58.00
Coins: 73.0
In the notebook: 73 coinsStart programming for free
10/10