Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 32 ยท Practice and Review

Lua Cheat Sheet

A Lua 5.4 cheat sheet: types, operators, control flow, functions, table and string library, metatables, coroutines and error handling at a glance.

This page is a quick reference for Lua 5.4. Each section is a few lines that jog your memory, with links to the lesson that explains the topic properly. Lua is not installed on this site, so the Lua code below is read-only, and the two editors use JavaScript to model rules you can try out (the same way the lessons do).

Lua is small on purpose: eight types, one compound structure (the table), and a handful of library tables (string, table, math, io, os, coroutine, utf8, debug). Where Lua 5.1 or LuaJIT differ, the section says so.

Lua in four ideas

Tables Arrays, records, objects and modules.
Metatables Operators and lookup rules for tables.
Closures Functions that remember variables.
Coroutines Pause and resume a function.

Everything else is built from these.

1 / 2

Basics

Comments start with --; long comments use --[[ ... ]]. Statements need no semicolons, and blocks end with end. print writes values separated by tabs and adds a newline. See Your First Lua Program.

LUA
-- single-line comment
--[[ multi-line
     comment ]]
local name = "Ada"          -- local variable
count = 0                   -- global (avoid)
local a, b = 1, 2           -- multiple assignment
a, b = b, a                 -- swap
local limit <const> = 10    -- 5.4: constant
print("Hello", name)        --> Hello    Ada

Types

nil, boolean, number, string, table, function, userdata and thread. Numbers are integers or floats (5.3 and later). Only nil and false are falsy. See Variables and Types.

LUA
type(nil)          --> "nil"
type(3)            --> "number"
math.type(3)       --> "integer"
math.type(3.0)     --> "float"
math.type("3")     --> nil     (not a number)
tonumber("0x10")   --> 16
tonumber("abc")    --> nil
tostring(12)       --> "12"

Operators

Kind Operators
Arithmetic + - * / // % ^ and unary -
Bitwise (5.3+) & | ~ << >> and unary ~
Comparison == ~= < <= > >=
Logical and or not (return operands)
String .. concatenation, # length
Precedence (high to low) ^, unary (not # - ~), * / // %, + -, .. (right), shifts, &, ~, |, comparisons, and, or

/ always gives a float, // is floor division, % takes the sign of the divisor, and ^ is a float power. Not equal is ~=, not !=. See Operators and Truthiness.

JS Division, floor division and modulo (a JavaScript model)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Control flow

LUA
if x > 0 then
  print("positive")
elseif x == 0 then
  print("zero")
else
  print("negative")
end

while n > 0 do n = n - 1 end
repeat n = n + 1 until n >= 3    -- body scope is visible in the condition

for i = 1, 10 do end             -- 1..10
for i = 10, 1, -2 do end         -- step -2
for i, v in ipairs(list) do end  -- array part, stops at first nil
for k, v in pairs(map) do end    -- all keys, unspecified order

for i = 1, 5 do
  if i % 2 == 0 then goto continue end
  print(i)
  ::continue::
end

There is no switch and no continue; use an if chain, a table of functions and goto continue. break leaves the innermost loop. See Conditionals, Loops and Iterating with pairs and ipairs.

Functions

LUA
local function add(a, b) return a + b end
local square = function(x) return x * x end

local function stats(...)           -- varargs
  local n = select("#", ...)
  local t = { ... }
  return n, t[1]
end

local function minmax(t)            -- multiple returns
  return math.min(table.unpack(t)), math.max(table.unpack(t))
end

local lo, hi = minmax({ 3, 1, 4 })
print(lo, hi)                       --> 1    4

print "hi"                          -- call sugar: one string...
print { 1, 2 }                      -- ...or one table argument

A call in the last position expands to all its results; elsewhere, or inside parentheses, it is cut to one value. return f(x) is a proper tail call. Use local function for recursion. See Functions, Varargs and Closures and Recursion and Tail Calls.

Strings

Strings are immutable byte sequences. Indexes start at 1 and negative indexes count from the end. Methods can be called with a colon: s:upper() is string.upper(s). See Strings.

LUA
local s = "Hello, Lua"
#s                         --> 10
s:upper()                  --> "HELLO, LUA"
s:sub(1, 5)                --> "Hello"
s:sub(-3)                  --> "Lua"
s:rep(2, "-")              --> "Hello, Lua-Hello, Lua"
s:find("Lua")              --> 8  10
s:find("l", 1, true)       --> 3  3   (plain search)
s:byte(1)                  --> 72
string.char(72, 105)       --> "Hi"
string.format("%5.2f|%d|%s|%q", 3.14159, 42, "x", "a\nb")
[[long string,
no escapes]]
Function Purpose
find(s, p, init, plain) start and end index of a match
match(s, p) first match or captures
gmatch(s, p) iterator over all matches
gsub(s, p, repl, n) replace; returns the new string and a count
format(fmt, ...) printf-style formatting
len, lower, upper, reverse, rep, sub, byte, char the basics

Patterns

Patterns are not regular expressions: there is no |, and quantifiers apply to single characters or classes only. Escape with %. See String Patterns.

Item Meaning
. %a %d %l %u %s %w %p any, letter, digit, lower, upper, space, alphanumeric, punctuation
%A %D ... complement of the class
[abc] [^abc] [a-z] set, negated set, range
* + - ? zero or more, one or more, lazy zero or more, optional
^ $ anchors
(...) capture; %1 refers back to it
%b() balanced parentheses
%f[%w] frontier: boundary where the next character is in the set
LUA
("key=value"):match("(%w+)=(%w+)")        --> "key"  "value"
("a1b22c333"):gsub("%d+", "#")            --> "a#b#c#"  3
for word in ("one two three"):gmatch("%a+") do print(word) end

Tables

LUA
local arr = { 10, 20, 30 }                 -- arr[1] == 10
local rec = { name = "Ada", age = 36 }     -- rec.name == rec["name"]
local mix = { "a", "b", x = 1, [10] = "ten" }

arr[#arr + 1] = 40                         -- append
rec.age = nil                              -- remove a key
#arr                                       --> 4

#t is reliable only for sequences without holes. Tables are compared and assigned by reference. NaN and nil cannot be keys. See Tables as Arrays and Dictionaries and Tables in Practice.

table function Purpose
insert(t, v) / insert(t, pos, v) append / insert and shift
remove(t) / remove(t, pos) pop last / remove and shift
concat(t, sep, i, j) join strings and numbers
sort(t, lt) in place, not stable; comparator is a strict less-than
unpack(t, i, j) values as separate results
pack(...) table with field n
move(a, f, e, t, b) copy a range between tables
JS A sort comparator and concat (a JavaScript model)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Metatables

LUA
local mt = {
  __index    = function(t, k) return 0 end,     -- missing key
  __newindex = function(t, k, v) rawset(t, k, v) end,
  __call     = function(self, ...) end,         -- t(...)
  __tostring = function(self) return "obj" end,
  __len      = function(self) return 0 end,
}
local t = setmetatable({}, mt)
getmetatable(t) == mt                           --> true
Metamethod Triggered by
__index, __newindex reading or writing an absent key
__add __sub __mul __div __mod __pow __unm __idiv arithmetic
__band __bor __bxor __shl __shr __bnot bitwise operators
__concat, __len .. and #
__eq, __lt, __le ==, <, <=
__call, __tostring, __name calling and printing
__close, __gc, __mode, __metatable to-be-closed, finalizer, weak tables, protection

rawget, rawset, rawequal and rawlen skip metamethods. See Metatables and Metamethods.

Classes

LUA
local Account = {}
Account.__index = Account

function Account.new(owner, balance)
  return setmetatable({ owner = owner, balance = balance or 0 }, Account)
end

function Account:deposit(n)          -- same as Account.deposit(self, n)
  self.balance = self.balance + n
end

local acc = Account.new("Ada")
acc:deposit(50)
print(acc.balance)                   --> 50

For inheritance, give the subclass a metatable whose __index is the parent class. See Objects and Classes and Inheritance and Mixins.

Errors

LUA
local ok, err = pcall(function() error("boom") end)
print(ok, err)                       --> false   file:line: boom

error({ code = 404 })                -- any value; tables carry data
error("no position added", 0)        -- level 0: no file:line prefix
assert(tonumber(input), "number expected")
xpcall(f, debug.traceback)           -- handler runs at the error point

local file <close> = io.open("data.txt")   -- 5.4: closed at end of scope

See Error Handling.

Coroutines and modules

LUA
local co = coroutine.create(function(a)
  local b = coroutine.yield(a + 1)
  return b * 2
end)
print(coroutine.resume(co, 1))       --> true   2
print(coroutine.resume(co, 10))      --> true   20
print(coroutine.status(co))          --> dead

local gen = coroutine.wrap(function() for i = 1, 3 do coroutine.yield(i) end end)

Statuses are suspended, running, normal and dead; coroutine.isyieldable() and coroutine.close(co) also exist. A module returns a table, and require caches it in package.loaded:

LUA
-- mathx.lua
local M = {}
function M.double(x) return x * 2 end
return M

-- main.lua
local mathx = require("mathx")      -- searched through package.path

See Coroutines and Modules and require.

Files, time and the system

LUA
local f = assert(io.open("notes.txt", "r"))
local text = f:read("a")            -- "a" all, "l" line, "n" number
f:close()

for line in io.lines("notes.txt") do print(line) end
io.write("no newline")

os.time()                           -- seconds since the epoch
os.date("%Y-%m-%d")                 -- formatted date
os.clock()                          -- CPU seconds
os.getenv("HOME")

The Lua 5.1 and LuaJIT forms differ: read("*a"), unpack as a global, no //, no goto in 5.1, no integer type. See Files and I/O.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which operator tests for inequality in Lua?

    Lua uses ~= for not equal. The operators != and <> do not exist.
  2. 2. What is 7 // 2 in Lua 5.4?

    // is floor division, so integer operands give the integer 3. The single slash / would give 3.5.
  3. 3. Which call removes the key age from the table rec?

    Assigning nil removes a key. Assigning false stores a false value, and table.remove works on array positions.
  4. 4. Where does require store a loaded module so later calls reuse it?

    package.loaded maps module names to the values the modules returned, and require returns that cached value.

Summary

  • Eight types; only nil and false are falsy; / is float division, // floor division, ~= inequality.
  • Tables hold everything; sequences start at 1; ipairs for arrays, pairs for all keys.
  • Strings are immutable, patterns use % escapes and have no alternation.
  • Metatables supply operators and inheritance; a:m() passes a as self.
  • Errors are values handled with pcall; coroutines are cooperative; modules return tables.

If you want to apply all of this, return to the Introduction to Lua or revisit the Exercises with Solutions.