Values, types and variables

Lua · Essentials · 10 min

Knowing the types and the local/global rule prevents the most common Lua bugs.

Lua is dynamically typed: values have types, variables don't. There are eight types, and type(v) returns the name as a string: nil, boolean, number, string, function, table, thread (coroutines) and userdata (C data).

Since 5.3 a number has two subtypes: integers (64-bit) and floats. 3 is an integer and 3.0 a float; math.type tells them apart. / always gives a float, // is floor division and ^ is exponentiation (always a float). Integer arithmetic wraps around on overflow instead of turning into a float.

Strings are immutable byte sequences, written with single quotes, double quotes, or long brackets [[ ... ]] for multi-line text. Concatenate with ..; #s is the length in bytes.

Variables are global by default. Assigning to an undeclared name creates a global, and reading a misspelled name silently gives nil. Always write local x = 1: locals are faster, scoped to their block, and cannot leak.

Lua supports multiple assignment, local a, b = 1, 2, and swapping with a, b = b, a. Extra values are discarded and missing ones become nil.

Example

local n, f = 10, 10.0
print(type(n), math.type(n), math.type(f))  --> number	integer	float
print(n == f)          --> true (same mathematical value)
print(7 / 2, 7 // 2)   --> 3.5	3
print(2 ^ 10)          --> 1024.0
print(math.maxinteger + 1 == math.mininteger) --> true (wraps)

local s = "Lua" .. " " .. 5.4
print(s, #s)           --> Lua 5.4	7

local a, b, c = 1, 2
print(a, b, c)         --> 1	2	nil
a, b = b, a
print(a, b)            --> 2	1

function leak() counter = 1 end  -- oops: creates a global
leak()
print(counter)         --> 1

Remember

  • Eight types; type(v) returns the name as a string
  • Numbers are integers or floats; / gives a float, // floors
  • Declare everything local; undeclared names are globals

Watch out for

  • A typo in a variable name silently reads nil instead of raising an error.

Check yourself

  1. What does 7 // 2 evaluate to in Lua 5.4?
  2. What happens when you assign x = 5 inside a function without local?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.lua.org/manual/5.4/manual.html#2.1