Lua, lesson 2
A variable is a name for a value. In Lua you create one with local:
If you leave out local, Lua creates a global variable that the whole program can see and
change. Globals are an easy way to get bugs: a typo silently creates a new global instead of
failing. Make local a habit for every variable.
Lua 5.5 also lets you declare globals explicitly with the new global keyword. You won't need
it in these lessons; just remember that global is now a reserved word, so you can't use it as
a variable name.
Lua is dynamically typed: values have types, variables don't. The same variable could hold
a number now and a string later (although doing that on purpose is rarely a good idea). The
built-in type function tells you the type of a value:
2 exercises to try what you just read.
nil.true or false.7 prints as 7,
but 7.0 prints as 7.0.Later you will meet tables and functions, which are values too.
Lua lets you attach the <const> attribute to a local. The compiler then refuses any
assignment to it, which is perfect for values that should never change:
Names use letters, digits and underscores, and can't start with a digit. They are case
sensitive. Lua code usually uses snake_case or camelCase for variables, and some people
write constants in UPPER_CASE. Avoid names that start with an underscore followed by capital
letters (like _VERSION), which Lua keeps for itself.
You can assign several variables in one statement. The values on the right are all evaluated first, which makes swapping easy:
The .. operator joins strings and turns numbers into text along the way:
To turn other values, such as booleans, into text, call tostring:
"ready: " .. tostring(true). Concatenating a boolean or nil directly is an error.
The starter declares four values for a game character. Print them on one line in exactly this format:
Use .. to join the pieces, and tostring for the boolean. The program reads no input.
Use a local variable savings that starts at 20. Change it three times and print it after
each step:
Expected output:
local name = "Rowan"
local level = 7
level = level + 1 -- variables can be reassigned
print(name, level) -- Rowan<tab>8print(type(42)) -- number
print(type(3.5)) -- number
print(type("tea")) -- string
print(type(true)) -- boolean
print(type(nil)) -- nillocal MAX_LIVES <const> = 3
-- MAX_LIVES = 4 -- error: attempt to assign to const variablelocal a, b = 1, 2
a, b = b, a
print(a, b) -- 2<tab>1local cups = 3
print(cups .. " cups of tea") -- 3 cups of teaRowan | level 7 | 42.5 HP | mage: trueStart: 20
After deposit: 35
Doubled: 70
After snack: 62