Variables & Types

Lua is dynamically typed: a variable does not carry a type, the value inside it does, and that value can change type across the variable's lifetime.

The eight types

Every value in Lua has exactly one of eight types. In everyday code you will mostly touch six of them:

TypeExample
nilthe absence of a value
booleantrue, false
number42, 3.14
string"hello"
table{1, 2, 3}
functionfunction() end

The other two, userdata and thread, show up when embedding (userdata is how a host like Luak hands a native object to a script) and with coroutines. type(v) returns which one a value is, as a string.

local versus global

A bare assignment creates a global. Almost always, you want local instead: it scopes the variable to the current block, and it is faster, since Lua does not have to look it up by name at runtime.

x = 10          -- global, avoid this
local y = 10    -- local, scoped to this block

Numbers

Since Lua 5.3, numbers have two subtypes: integer and float. Literals without a decimal point or exponent are integers; everything else is a float. Division with / always produces a float; // is floor division and keeps the integer subtype when both operands are integers.

print(7 / 2)   -- 3.5
print(7 // 2)  -- 3
print(7 % 2)   -- 1

Strings

Single and double quotes both work and mean the same thing. Long strings use double square brackets and ignore escape sequences, handy for multi-line text. .. concatenates; there is no + for strings.

local a = 'single quotes'
local b = "double quotes"
local c = [[
a long string,
spanning lines, no escaping needed
]]

print(a .. ", " .. b)
print(#b) -- length: 13

Truthiness: the one everyone forgets

Only nil and false are falsy. Every other value, including 0 and the empty string "", is truthy. Coming from JavaScript, Python or C, this is the single most common early bug.

if 0 then
    print("0 is truthy in Lua") -- this runs
end