Values, Types and Variables

3.1 The Eight Types

Absence of a value; uninitialized variables are nil true, false 42, 3.14, 0xFF, 1e10

Subtypes integer (64-bit) and float (double) since 5.3 "hi", 'hi', [[long]] Immutable byte sequences print, function() end First-class values (Lua or C functions) {}, {1, 2}, {x = 1} The only data structure C data (files, objects from C) Full and light userdata

print(type(nil), type(true), type(42), type("x"), type(print), type({}), type(io.stdout), type(coroutine.create(print)))
--> nil  boolean  number  string  function  table  userdata  thread
print(math.type(1), math.type(1.0), math.type("1"))   --> integer  float  nil

3.2 Variables: Global vs Local

Locals are faster (stored in registers) and avoid name clashes. Globals are table lookups.

Lua 5.4 limits a function to 200 locals.

x = 10                 -- global variable (stored in the _ENV table, usually _G)
local y = 20           -- local variable (lexically scoped): ALWAYS prefer local
local a, b, c = 1, 2   -- multiple assignment: c is nil
local p, q = 1, 2, 3   -- the extra value 3 is discarded
a, b = b, a            -- swap

do
    local inner = "only visible in this block"
end
print(inner)           --> nil (it's an undefined global)

3.3 Truthiness

Only nil and false are falsy. Everything else is truthy, including 0 and "" (unlike C, Python, and JavaScript).

if 0 then print("0 is true in Lua") end
if "" then print("empty string is true") end
local value = nil
local name = value or "default"           -- idiomatic default value

3.4 Type Conversion

Relying on string↔number coercion is discouraged. Convert explicitly with tonumber/tostring.

print(tonumber("42"), tonumber("3.14"), tonumber("0x1F"), tonumber("abc"))   --> 42  3.14  31  nil
print(tonumber("ff", 16), tonumber("777", 8), tonumber("1010", 2))           --> 255  511  10
print(tostring(42), tostring(nil), tostring({}))                              --> 42  nil  table: 0x...
print("10" + 5)      --> 15    (string coerced to a number; in 5.4 this is done by string metamethods)
print(10 .. 20)      --> 1020  (numbers coerced to strings; note the spaces around ..)
print(math.tointeger(3.0), math.tointeger(3.5))   --> 3  nil (5.4 returns "fail", which is nil)
print(3 // 1, 3.7 // 1, math.floor(3.7))          --> 3  3.0  3