Variables and the local Keyword

A variable is a name for a value. You create one with the word local, then a name, an = sign and a value:

local score = 10
print(score)
print(score + 5)

Output:

10
15

The first line declares the variable score and gives it the value 10. After that, when you write score, Lua uses the value 10.

To change the value, assign again. Don't write local the second time:

score = 25
print(score)

Output:

25

You can also declare several variables in one line. Lua matches the values to the names by position:

local lives, level = 3, 1
print(lives, level)

Output:

3	1

Names that have no value

What happens if you use a name that you never gave a value?

local score = 10
print(scroe)
print(Score)

Output:

nil
nil

There is no error. Lua prints nil, its value for "nothing". Every name you never assigned holds nil. Here scroe is a typo, and Score is a different name because Lua names are case sensitive. So if a value is nil when you don't expect it, check the spelling first.

Why write local?

If you leave out local, the variable still works:

count = 5
print(count)

Output:

5

But now count is a global variable. Every part of the program can see it and change it. In big programs, such as a game with many scripts, two scripts can use the same global name by accident and change each other's values. A local variable is only visible in the part of the code where you declared it. So always write local, unless you really need a global.

Names can use letters, digits and underscores (_), but they can't start with a digit. Choose names that say what the value means, like score or playerName.

In the exercise, create two variables and then change one of them.