Lua Variables
A variable is a name that holds a value. Writing local before the name creates the variable.
local stores a value in a name
local creates the variable score and stores 10 in it. print shows the stored value.
local score = 10
print(score)A stored value can be replaced
The variable level first holds 1 and then holds 2. Each print shows the value held at that moment.
local level = 1
print(level)
level = 2
print(level)One print can show two variables
Two variables hold a name and a score. One print shows both values, split by a tab.
local name = "Sam"
local score = 50
print(name, score)Example
local name = "Ava"
local score = 120
local level = 4
print("Player", name)
print("Score", score)
print("Level", level)Key points
- local: the word local creates a variable, as in local score = 10.
- Assignment: the = sign stores a value in a variable.
- Reassignment: storing a new value in a variable replaces the old value.
- Names: a name can use letters, digits, and underscores.
- First character: a name cannot start with a digit.
- Case: Score and score are two different names, because letter case matters.
In this example, local creates three variables for a player profile. The first print shows the player name beside its label. The next two prints show the score and the level in the same way.
Note
a name assigned without local becomes a global, so local is the habit to use every time.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line creates a local variable named lives that holds 3?