Lua: reference

A small embeddable language for games and scripts: tables, closures and coroutines.

Program structure

Minimal program

There is no separate main: the script runs from top to bottom. print puts a tab between arguments and moves to a new line, while io.write does not.

print("Hello, world!")
print("a", "b", 42)
io.write("No line break")
io.write("\n")
-- comment to the end of the line
--[[ multi-line
comment ]]

Running

Scripts with the .lua extension are run by the lua interpreter. The -e flag runs a single line, and running with no arguments opens an interactive console.

lua hello.lua

lua -e "print(2 + 3)"

lua    -- interactive console

Variables and types

Local and global variables

local creates a variable visible only in the current block. Without local the variable becomes global. Multiple assignment lets you swap variables in one step.

local name = "Olena"
local score = 0
score = score + 10
count = 5
local a, b = 1, 2
a, b = b, a
print(name, score, count, a, b)

Types

Main types: number, string, boolean, nil, table, function. Lua 5.4 has integers and floats, // is integer division, and / always gives a float.

print(type(42), type(3.14), type("s"))
print(type(true), type(nil), type({}))
print(type(print))
print(math.type(7), math.type(7.0))
print(7 // 2, 7 / 2, 7 % 3, 2 ^ 10)

Type conversion

tonumber converts a string to a number and returns nil if that is impossible. tostring makes a string from any value, and math.floor rounds down.

print(tonumber("12") + 1)
print(tonumber("abc"))
print(tostring(42) .. "!")
print(tonumber("ff", 16))
print(math.floor(3.9), math.ceil(3.1))
print(10 == 10.0)

Strings

Concatenation and length

Strings are joined with the .. operator, and # returns the length. Double and single quotes are equivalent, and [[ ... ]] gives a multiline string with no escaping.

local a = "Hello"
local b = 'World'
print(a .. ", " .. b .. "!")
print(#a)
print("x" .. 1 .. 2)
local long = [[A string
across two lines]]
print(long)

The string library

String methods are called with a colon: s:upper(). Indexing in sub and find starts at 1, and string.format works like printf in C.

local s = "Hello, World"
print(s:upper(), s:lower())
print(s:sub(1, 5))
print(s:find("World"))
print(s:rep(2, "-"))
print(s:reverse())
print(string.format("%s: %d, %.2f", "x", 7, 3.14159))

Patterns

Lua has its own patterns instead of regular expressions: %d digit, %a letter, %w letter or digit, + repeat. Parentheses capture parts of a match, and gmatch iterates over all matches.

local s = "a1b22c333"
print(s:match("%d+"))
print(s:gsub("%d", "#"))
for w in ("one two three"):gmatch("%a+") do
  print(w)
end
print(("key=value"):match("(%w+)=(%w+)"))

Conditions

if, elseif, else

The condition is not wrapped in parentheses, the block ends with the word end, and the branch is spelled elseif. Inequality is written ~=, and the logical operators are and, or, not.

local n = 15
if n < 10 then
  print("few")
elseif n < 20 then
  print("medium")
else
  print("many")
end
print(n ~= 15, not (n > 5))

Truthiness and and/or

Only nil and false are falsy, while 0 and an empty string count as true. The expression a and b or c serves as a ternary operator, and x or value sets a default.

print(nil and 1, false or "default")
print(0 and "zero is also true")
print("" and "an empty string too")
local x = nil
local y = x or 100
local z = (5 > 3) and "yes" or "no"
print(y, z)

Loops

Numeric for

The form for i = start, stop, step includes both bounds, and the step defaults to 1. The loop variable is local, and changing it does not affect the number of iterations.

for i = 1, 3 do
  print(i)
end
for i = 10, 1, -4 do
  print(i)
end
for i = 0, 1, 0.5 do
  print(i)
end

while and repeat

while checks the condition before a step and repeat ... until after it, so the body runs at least once. The condition in until can see locals from the loop body.

local n = 0
while n < 3 do
  n = n + 1
end
print(n)
local k = 10
repeat
  k = k - 3
until k < 0
print(k)

break and goto continue

break leaves the loop. Lua has no continue statement, so goto to a ::continue:: label at the end of the loop body is used instead.

for i = 1, 10 do
  if i % 2 == 0 then goto continue end
  if i > 7 then break end
  print(i)
  ::continue::
end

Functions

Defining a function

A function is an ordinary value and can be stored in a variable. It can return several values separated by commas. For recursion, declare it as local function.

local function add(a, b)
  return a + b
end
local mul = function(a, b) return a * b end
print(add(2, 3), mul(2, 3))
local function minmax(a, b)
  if a < b then return a, b end
  return b, a
end
print(minmax(9, 4))

Variable number of arguments

Three dots ... accept any number of arguments. They are collected into the table {...}, and select("#", ...) returns the number of arguments.

local function sum(...)
  local total = 0
  for _, v in ipairs({...}) do
    total = total + v
  end
  return total, select("#", ...)
end
print(sum(1, 2, 3, 4))
print(select(2, "a", "b", "c"))

Closures

An inner function remembers the local variables of the outer one even after it has finished. Each call to counter() creates its own independent counter n.

local function counter()
  local n = 0
  return function()
    n = n + 1
    return n
  end
end
local c = counter()
print(c(), c(), c())

Tables

Table as an array

A table is the only data structure in Lua. As an array it is indexed from 1, #t gives the length, and table.insert, table.remove, table.sort change it in place.

local t = {10, 20, 30}
table.insert(t, 40)
table.insert(t, 1, 5)
print(#t, t[1], t[#t])
print(table.remove(t))
print(table.concat(t, ", "))
table.sort(t, function(a, b) return a > b end)
print(table.concat(t, " "))

Table as a dictionary

The form t.key is shorthand for t["key"]. Assigning nil removes a key, and a missing key gives nil. The traversal order of pairs is not guaranteed.

local p = {name = "Olena", age = 17}
p.city = "Dnipro"
p["age"] = 18
p.city = nil
for k, v in pairs(p) do
  print(k, v)
end
print(p.missing)

ipairs and nested tables

ipairs walks elements from 1 up to the first nil, while pairs takes all pairs. Nested tables form matrices, and holes with nil make the length # unreliable.

local grid = { {1, 2}, {3, 4} }
print(grid[2][1])
for i, row in ipairs(grid) do
  print(i, #row)
end
local list = {"a", "b", nil, "d"}
print(#list >= 2)

Tables as objects

Methods and self

The form obj:method(x) is the same as obj.method(obj, x): the object automatically becomes the first parameter self. This way tables hold both data and behavior.

local acc = {balance = 0}
function acc:deposit(n)
  self.balance = self.balance + n
end
function acc.show(a)
  print(a.balance)
end
acc:deposit(50)
acc:show()

A class via a metatable

A metatable with an __index field says where to look for missing fields and methods. setmetatable attaches it to an object, so all instances share the class methods.

local Dog = {}
Dog.__index = Dog
function Dog.new(name)
  return setmetatable({name = name}, Dog)
end
function Dog:speak()
  return self.name .. " says woof"
end
local d = Dog.new("Rex")
print(d:speak())

Inheritance

A child class itself has a metatable with __index pointing to the parent. Method lookup follows the chain: the object, its class, then the parent class.

local Animal = {}
Animal.__index = Animal
function Animal:kind() return "animal" end
local Cat = setmetatable({}, {__index = Animal})
Cat.__index = Cat
function Cat:meow() return "meow" end
local c = setmetatable({}, Cat)
print(c:meow(), c:kind())

Metatables

Operators via metamethods

The metamethods __add, __eq, __lt, __tostring define how a table behaves with operators and functions like print. They are placed in the metatable.

local V = {}
V.__index = V
V.__add = function(a, b) return setmetatable({x = a.x + b.x}, V) end
V.__tostring = function(v) return "V(" .. v.x .. ")" end
V.__eq = function(a, b) return a.x == b.x end
local a = setmetatable({x = 1}, V)
local b = setmetatable({x = 2}, V)
print(tostring(a + b), a == b)

__index, __newindex, __call

__index intercepts reads of missing keys, __newindex writes of new ones, and __call lets you call a table as a function. rawset writes bypassing the metatable.

local t = setmetatable({}, {
  __index = function(_, k) return "none " .. k end,
  __newindex = function(tbl, k, v) rawset(tbl, k, v * 2) end,
  __call = function(_, x) return x + 1 end,
})
print(t.foo)
t.a = 5
print(t.a, t(10))

Coroutines

create, resume, yield

A coroutine is a function that can be paused. resume starts or continues it, and yield hands a value back and waits. The state is shown by coroutine.status.

local co = coroutine.create(function(a)
  print("start", a)
  local b = coroutine.yield(a + 1)
  print("got", b)
  return "done"
end)
print(coroutine.resume(co, 10))
print(coroutine.resume(co, "x"))
print(coroutine.status(co))

A generator via wrap

coroutine.wrap returns a function that continues the coroutine on every call. It is a handy way to build an iterator for a for ... in loop.

local function range(n)
  return coroutine.wrap(function()
    for i = 1, n do coroutine.yield(i) end
  end)
end
for i in range(3) do
  print(i)
end

Modules and errors

A module as a table

A module is a file that returns a table. The require function loads it once and caches the result. Anything that should not be exposed stays local.

local M = {}
function M.square(x) return x * x end
M.pi = 3.14159
-- mymath.lua ends with: return M
-- main.lua: local mymath = require("mymath")
print(M.square(4), M.pi)

pcall and error

pcall runs a function and returns true and the result, or false and an error message. error throws an error, and you can pass either a string or a table to it.

local ok, err = pcall(function()
  error("something went wrong")
end)
print(ok, err)
print(select(2, pcall(error, {code = 42})).code)
local ok2, v = pcall(function() return 1 + 1 end)
print(ok2, v)

assert and xpcall

assert(condition, message) throws an error if the condition is false. xpcall also takes an error handler. I/O functions like io.open return nil instead of raising an error.

print(pcall(assert, false, "check failed"))
print(xpcall(function() error("boom") end,
  function(m) return "handled: " .. m end))
local f = io.open("no_such_file.txt")
print(f)

What is next

A lessons course for this language is on the way, and the reference is already available.

A course is on the way. For now only the reference is available; lessons and tasks will follow.