11. Variables and types

Chapter 7 wrote text directly inside print calls. That works, but any information needed in more than one place has to be retyped every time. Variables fix that. A variable is a name that stands in for a value, so you write the value once and reuse it.

Declaring a variable

The most common shape of a variable declaration in Lua:

local name = "Keiko"
print(name)

Four things are going on in that first line:

  • local is a keyword meaning create a new variable that lives inside this file. Always use it. The reason is in the box below.
  • name is the variable's name. You pick it.
  • = is the assignment operator. It puts the value on the right into the variable on the left. It does not mean "equal to" the way it does in maths.
  • "Keiko" is the value being stored.

Now name stands in for the string "Keiko", so print(name) prints Keiko.

If you forget local, the variable still works, but it becomes a global variable. Globals are shared across the whole program and cause hard-to-find bugs as it grows. Always write local the first time you use a name. The rest of this book does.

Changing a variable

A variable's value can change. Use = again, without local:

local score = 0
print(score)   -- prints 0
score = 50
print(score)   -- prints 50

local belongs only on the first mention of a name. Repeating it makes a separate variable that happens to share the name, which is almost never what you want.

Open exercises/11/01-variables.lua. Change the starting value of score and run the file. Both print calls should change in step.

Types

In Lua a value also has a type, not just data. The four types you need right now:

  • string — text, written between quotes: "hello", 'a', "" (the empty string).
  • number — any number, with or without a decimal point: 0, -7, 3.14.
  • boolean — exactly two values: true and false. No quotes.
  • nil — the absence of any value at all.

type() is a built-in function that returns a value's type as a string:

print(type("hello"))   -- string
print(type(7))         -- number
print(type(true))      -- boolean
print(type(nil))       -- nil

Variable names

You pick variable names, but Lua has rules about which are allowed:

  • They can contain letters, digits, and the underscore _.
  • They cannot start with a digit. level1 is fine; 1level is not.
  • They are case sensitive. Score, score, and SCORE are three different names.
  • They cannot be one of Lua's reserved words: and, break, do, else, elseif, end, false, for, function, goto, if, in, local, nil, not, or, repeat, return, then, true, until, while. You will meet most of these later.

Beyond the rules, follow these habits:

  • Choose meaningful names. player_name beats n. hit_points beats hp once code gets long, though hp is fine for short scripts.
  • Lower case with underscores is the usual Lua style: max_score, enemy_count. CamelCase (maxScore) is also common, especially in Roblox. Pick one and stick to it inside a file.

Printing a variable

print does not need quotes around variable names. Quotes are only for text you type directly:

local level = 7
print("Level:", level)        -- Level:    7
print("Level: " .. level)     -- Level: 7

The first line uses print's tab separator. The second uses .. to glue "Level: " and the value of level into one string.

.. between a string and a number works because Lua converts the number to text on the fly. That convenience does not make numbers and strings the same thing. 7 and "7" are different types, even though they look alike.

Multi-assignment

Lua lets you declare several variables and assign several values on one line. Names on the left pair with values on the right by position:

local name, level = "Keiko", 7
print(name, level)   -- Keiko    7

This groups related declarations neatly. It also enables a handy trick — swapping two variables in one step:

local a, b = 1, 2
a, b = b, a
print(a, b)   -- 2  1

Lua reads the whole right side first, then assigns. So a, b = b, a takes the current b and a and puts them in opposite slots.

Homework

Homework starters are in exercises/11/homework/.

Problem 1 — Player vitals

Open exercises/11/homework/01-player-vitals.lua. Declare four local variables called name, level, hit_points, and alive, with values of your choice. The first must be a string, the next two numbers, and the fourth a boolean. Print each on its own line with a label, like Name: Keiko.

Problem 2 — Type checker

Open exercises/11/homework/02-type-checker.lua. Use type() to print the type of each of these five values, one per line:

  • the string "world",
  • the number 42,
  • the number 3.14,
  • the boolean false,
  • nil.

Problem 3 — Rename and reassign

Open exercises/11/homework/03-rename-and-reassign.lua. The starter file has three variables a, b, and c with random-looking values. Rename them to something meaningful for their values, print the originals, change all three, then print them again.

Challenge — The nil mystery

Open exercises/11/homework/04-nil-mystery.lua. Declare a local variable with no value and print its type. Then give it a string value and print its type again. Add a short multi-line comment explaining, in your own words, what nil means.

Stuck or finished? Open the homework solutions page.