Skip to content
LumenaryAcademy
Foundations 55 min

Values, strings and control flow

Lua's eight types, numbers and strings, truth, local and global variables, and every kind of loop and branch.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

A small language, precisely defined

Lua's whole syntax fits on one page of its reference manual. That smallness is a gift to a learner: after this lesson you will know essentially every kind of value and statement the language has. What remains, in later lessons, is learning what can be built from them.

Small does not mean vague. Lua is precise about things that other scripting languages leave fuzzy: exactly which values count as false, when a number is an integer and when it is a float, what happens when an integer overflows, how a string's length is measured. Knowing those rules exactly is what separates code that works from code that works on the test data.

This lesson also covers one of Lua's few famous pitfalls, global by default, and the new tool Lua 5.5 offers against it.

DefinitionsH

Eight types, and what is true

Definition— Lua's types

Every value in Lua has one of eight types: nil (the single value nil, meaning "no value"), boolean (true and false), number (integers and floating-point numbers), string (immutable sequences of bytes), function, table (the one data structure), userdata (blocks of memory managed by C code, such as open files) and thread (a coroutine). Variables have no types; values do, and type(v) names a value's type.

lua
-- Every value has one of eight types.
local samples = { nil, true, 42, 3.5, "moon", print, {}, coroutine.create(print) }
for i = 1, 8 do
  io.write(type(samples[i]), " ")
end
print()

-- Only nil and false are false. Zero and the empty string are true.
for _, v in ipairs({ 0, "", "false" }) do
  print(string.format("%q", v), v and "is true" or "is false")
end
print("nil", nil and "is true" or "is false")

-- Numbers: integers and floats are two subtypes of number.
print(math.type(7), math.type(7.0), 7 == 7.0)
print(7 / 2, 7 // 2, 7.0 // 2, 7 % 3, -7 % 3, 2 ^ 10)
print(math.maxinteger, math.maxinteger + 1 == math.mininteger)   -- integers wrap around
print(0.1 + 0.2, 0.1 + 0.2 == 0.3, 1 / 3)
print(tonumber("42"), tonumber("0x1F"), tonumber("3.5e2"), tonumber("12 apples"))
print(math.tointeger(8.0), math.floor(3.7), 3 | 5, 6 & 3, 1 << 10)

It printed:

text
nil boolean number number string function table thread 
0	is true
""	is true
"false"	is true
nil	is false
integer	float	true
3.5	3	3.0	1	2	1024.0
9223372036854775807	true
0.30000000000000004	false	0.33333333333333331
42	31	350.0	nil
8	3	7	2	1024

Truth

Only nil and false are false. Every other value is true, including the number 0, the empty string "" and the string "false". Programmers coming from C, Python or JavaScript expect 0 and "" to be false, and this is a real source of bugs in their first Lua programs.

The line v and "is true" or "is false" uses Lua's logical operators, which return one of their operands rather than true or false: a and b gives a if a is false or nil, otherwise b; a or b gives a if a is true, otherwise b. This gives two everyday idioms, x = x or default and cond and value1 or value2, and one trap, below.

Numbers

Since Lua 5.3, the number type has two subtypes: 64-bit integers and double-precision floats. math.type tells them apart, and 7 == 7.0 is true because comparison is mathematical.

  • / always gives a float: 7 / 2 is 3.5.
  • // is floor division: it rounds towards minus infinity, giving an integer for integer operands (7 // 2 is 3) and a float otherwise.
  • % is the matching modulo, whose result has the sign of the divisor: -7 % 3 is 2.
  • ^ always gives a float: 2 ^ 10 is 1024.0. Use 1 << 10 for integer powers of two.
  • Integers wrap around on overflow, as in C: math.maxinteger + 1 is math.mininteger. Floats do not wrap; they lose precision.

Lua 5.5 prints floats so that they can be read back exactly: it tries 15 significant digits, and if those do not reproduce the same number it uses 17. So 0.1 + 0.2 prints as 0.30000000000000004, which honestly shows why 0.1 + 0.2 == 0.3 is false. Lua 5.4 printed only 14 digits and showed 0.3, hiding the difference. A float with an integral value prints with .0, which is how you can see 2 ^ 10 is a float.

tonumber converts strings, including hexadecimal and exponent notation, and returns nil for anything that is not entirely a number: "12 apples" is not.

Misconception

"cond and a or b is exactly like C's cond ? a : b." Almost. If a is false or nil, the and gives that false value, and or then picks b even though the condition was true. enabled and false or true is always true. Use the idiom only when the middle value can never be false or nil, and use an if statement otherwise.

Worked examplesH

Strings

A Lua string is an immutable sequence of bytes. Literals use single or double quotes (they mean the same thing) with C-style escapes such as \n, \t, \" and \u{263A} for a Unicode character in UTF-8. Long strings, written between [[ and ]], span lines and ignore escapes; if the text itself contains ]], add equal signs: [==[ ... ]==].

The string library does the work, and every string can call its functions as methods: s:upper() is string.upper(s).

lua
local city = "Belo Horizonte"
print(#city, city:upper(), city:sub(1, 4), city:sub(-8))
print(city:find("Horiz"))                 -- start and end positions
print(city:find("Rio"))                   -- not found: nil
print(city:rep(2, " / "))
local squeezed = city:gsub(" ", "")       -- gsub also returns a count; we keep the string
print(("%s has %d letters"):format(city, #squeezed))

local poem = [[
Long strings use double brackets
and keep their line breaks.]]
print(poem)
print("tab:\tend", "quote: \"hi\"", "unicode: \u{263A}")

-- Strings are bytes. The utf8 library counts characters.
local fruit = "açaí"
print(#fruit, utf8.len(fruit), fruit:upper())

-- Coercion: arithmetic on numeric strings, concatenation of numbers.
print("10" + 5, "3" * "4", 10 .. 20, "10" == 10)

-- Comparison is by byte value, so case matters.
print("apple" < "banana", "Zebra" < "apple", "10" < "9")

It printed:

text
14	BELO HORIZONTE	Belo	orizonte
6	10
nil
Belo Horizonte / Belo Horizonte
Belo Horizonte has 13 letters
Long strings use double brackets
and keep their line breaks.
tab:	end	quote: "hi"	unicode: ☺
6	4	AçAí
15	12	1020	false
true	true	true

What to notice:

  • Positions count from 1, and negative positions count from the end: city:sub(-8) is the last eight bytes. sub(i, j) includes both ends.
  • find returns the start and end of a match, or nil. Many Lua functions return several values; lesson 4 explains how that works.
  • gsub (global substitution) returns the new string and the number of replacements. Assigning the call to one variable keeps only the first result.
  • # counts bytes. "açaí" has four characters but six bytes in UTF-8, because ç and í take two bytes each. utf8.len counts characters. The string functions work on bytes too, which is why upper changed only the ASCII letters.
  • Arithmetic on a string that looks like a number converts it ("10" + 5 is 15), and concatenating a number converts it to a string. Comparison never converts: "10" == 10 is false.
  • Strings compare byte by byte, so "Zebra" < "apple" (capital letters have smaller codes) and "10" < "9".

Two performance notes that matter in practice. Strings are immutable, so building a long string with s = s .. piece in a loop copies the whole string each time, which gets slow for large outputs; collect the pieces in a table and join them once with table.concat (lesson 3). And identical strings are stored only once and compared in constant time, so using strings as keys and labels is cheap.

string.find, match, gmatch and gsub also understand patterns, a small cousin of regular expressions (for example "%d+" means "one or more digits"). Lesson 8's project uses them, and lesson 3 shows a first one.

Worked examplesH

Branches and loops

lua
local temperature = 31
if temperature >= 30 then
  print("hot")
elseif temperature >= 15 then
  print("mild")
else
  print("cold")
end

-- Numeric for: start, limit, optional step; both ends included.
for i = 10, 1, -3 do io.write(i, " ") end
print()

-- while tests first; repeat tests last, and its body's locals are visible in until.
local n, steps = 27, 0
while n ~= 1 do
  if n % 2 == 0 then n = n // 2 else n = 3 * n + 1 end
  steps = steps + 1
end
print("Collatz steps from 27: " .. steps)

local guess = 0
repeat
  guess = guess + 7
  local square = guess * guess
until square > 1000
print("first multiple of 7 whose square exceeds 1000: " .. guess)

-- Lua has break but no continue; goto handles the rare case you need one.
for i = 1, 10 do
  if i % 3 == 0 then goto continue end
  if i > 8 then break end
  io.write(i, " ")
  ::continue::
end
print()

-- Multiple assignment evaluates every right-hand side first.
local a, b = 1, 2
a, b = b, a
print(a, b)

-- and/or return one of their operands: the idioms for defaults and choices.
local nickname = nil
print(nickname or "guest", temperature > 25 and "shorts" or "coat")

It printed:

text
hot
10 7 4 1 
Collatz steps from 27: 111
first multiple of 7 whose square exceeds 1000: 35
1 2 4 5 7 8 
2	1
guest	shorts

The full set:

  • if cond then ... elseif cond then ... else ... end. Note the single word elseif.
  • while cond do ... end tests before each pass. Lua's "not equal" operator is ~=.
  • repeat ... until cond tests after each pass, so the body runs at least once. Unusually, a local declared inside the body is still visible in the until condition, which the square example uses.
  • Numeric for. for i = start, limit, step do ... end includes both ends; the step defaults to 1 and may be negative. The limits are evaluated once, before the loop starts. In Lua 5.5 the loop variable is read-only: assigning to i inside the loop is a compile error. If you need a changing copy, write local i = i at the top of the body.
  • Generic for. for k, v in pairs(t) and for i, v in ipairs(t) walk tables, as you saw in lesson 1; lesson 3 covers them and lesson 4 shows how to write your own iterators.
  • break leaves the innermost loop. Lua has no continue. When you need one, goto continue with a label ::continue:: at the end of the loop body is the accepted idiom (labels and goto arrived in Lua 5.2). Do not use goto for anything more creative.
  • Multiple assignment. a, b = b, a evaluates all the right-hand values before assigning, so it swaps.
Worked examplesH

Local, global and Lua 5.5's declarations

Definition— Local and global variables

A local variable is declared with local and is visible from the next statement to the end of the enclosing block (a function body, a do ... end, a loop body, or the file). Any other name is global: by default, reading an undeclared name reads a global (nil if it was never set), and assigning to it creates or changes a global. Globals are stored in a table, the environment, which is how lesson 1's load could give a script its own.

lua
-- Without 'local', assignment creates a global variable.
local function count_up()
  counter = (counter or 0) + 1      -- a global: probably a bug
  local private = 1                 -- a local: gone when the function returns
  return private
end
count_up(); count_up()
print("global counter:", counter, "private:", private)

-- Locals are block scoped, and an inner local shadows an outer one.
local x = "outer"
do
  local x = "inner"
  print(x)
end
print(x)

-- <const> locals cannot be assigned again; the compiler checks.
local limit <const> = 100
print(load("local limit <const> = 100; limit = 5"))

-- Lua 5.5: once a chunk declares any global, every name must be declared.
print(load("global print; print('declared'); total = 1"))
local strict = load("global print, tostring; local n = 3; print('n is ' .. tostring(n))")
strict()

-- Lua 5.5: the control variable of a for loop is read-only.
print(load("for i = 1, 3 do i = i * 2 end"))
print("limit is " .. limit)

It printed:

text
global counter:	2	private:	nil
inner
outer
nil	[string "local limit <const> = 100; limit = 5"]:1: attempt to assign to const variable 'limit'
nil	[string "global print; print('declared'); total = 1"]:1: variable 'total' not declared
n is 3
nil	[string "for i = 1, 3 do i = i * 2 end"]:1: attempt to assign to const variable 'i'
limit is 100

The function count_up meant to keep a counter but, by leaving out local, created a global named counter that any code anywhere could read or overwrite. Meanwhile private vanished at the end of the function, and reading it outside gave nil silently: no error, no warning. Two rules follow:

  1. Write local every time you introduce a variable, including for functions (local function name ... end). Locals are also faster: they live in virtual machine registers, while globals need a table lookup.
  2. Use a checker. The linter luacheck reports every global that is set or read but not declared, and most Lua teams run it on every change.

local name <const> = value (Lua 5.4) declares a constant that the compiler refuses to reassign; the error appeared as soon as load compiled the offending chunk, before anything ran.

Global declarations in Lua 5.5

Lua 5.5 adds a direct defence: the global keyword. Once a chunk or block contains any global declaration, Lua stops treating undeclared names as globals within its scope. Every name must then be declared as a local or a global, and anything else is a compile-time error. In the program, the chunk global print; ... total = 1 was rejected because total was never declared, while the chunk declaring both print and tostring compiled and ran.

lua
global print, string, table   -- the globals this file uses
global<const> *               -- or: every other name is a read-only global

global * declares all remaining names as globals (the old behaviour), and global<const> * makes them read-only, which stops a script from accidentally replacing print or string. A file with no global declaration behaves exactly as in Lua 5.4, so old code keeps working, except that global is now a reserved word and can no longer be used as a variable name. Because Lua 5.5 is new, most code you read today does not use global yet; luacheck remains the common tool, and global declarations are a good habit for new code that only needs to run on 5.5.

ExplanationH

Habits worth forming now

  • local everywhere, at the narrowest scope that works. Declare variables where you first assign them.
  • Remember that 0 is true. Test if count > 0, not if count, and if s ~= "", not if s.
  • Know your number subtypes. When an integer matters (an index, a count), use // or math.tointeger, and use math.type when debugging a value that prints as 3.0.
  • Build strings with table.concat, not .. in a loop, when the output is large.
  • Remember that strings are bytes. For user-visible text in languages other than English, use the utf8 library for lengths and positions, and do not expect upper and lower to handle non-ASCII letters.
  • Format numbers explicitly with string.format whenever output will be read by people or compared in tests, so that integer and float subtypes, and changes in printing between Lua versions, cannot surprise you.
Exercises

Exercises

1. Values, strings and control flow

Warm-upComputational

What does this program print?

print(7 // 2 .. " " .. 7 / 2 .. " " .. 2 ^ 3)

2. Values, strings and control flow

Warm-upComputational

What does this program print?

local function check(v)
  if v then return "T" else return "F" end
end
print(check(0) .. check("") .. check(nil) .. check(false) .. check("false"))

3. Values, strings and control flow

CoreComputational

What number does this program print?

print(-7 // 2)

4. Values, strings and control flow

CoreComputational

What does this program print?

local enabled = true
local value = enabled and false or "default"
print(value)

5. Values, strings and control flow

CoreComputational

The source file is saved as UTF-8. What number does this program print?

print(#"naïve")

6. Values, strings and control flow

Warm-upComputational

What does this program print?

for i = 1, 10, 4 do io.write(i, ",") end
print()

7. Values, strings and control flow

StretchComputational

What does this program print?

local function add_five()
  total = (total or 0) + 5
end
add_five()
add_five()
local total = 1
print(total .. " " .. _G.total)

8. Values, strings and control flow

CoreHuman

A Lua 5.5 file begins with global print, string. Later in the same file it assigns count = 0 without declaring count. What happens?

Choose one

Further reading and resources