Skip to content
AgileLogics

Lua Cheat Sheet

Learn Lua from the basics →

Variables & Types

local name = "Ada"
Local variable (always prefer local)
local a, b = 1, 2
Multiple assignment
type(x)
nil, boolean, number, string, table, function, thread, userdata
tonumber("42") / tostring(42)
Convert (tonumber returns nil on failure)
math.type(3) / math.type(3.0)
"integer" / "float" (Lua 5.3+)
x = x or "default"
Default value (only nil and false are falsy)

Strings

"Hello, " .. name
Concatenation
#s
Length in bytes
string.format("%s is %d", name, age)
Formatted string
s:upper() / s:lower() / s:rep(3)
Method call syntax on strings
s:sub(2, 4)
Substring (1-based, inclusive)
[[multi-line string]]
Long string, no escapes processed

Control Flow

if x > 0 then ... elseif x < 0 then ... else ... end
Conditional
for i = 1, 10 do ... end
Numeric loop (inclusive); for i = 10, 1, -1 counts down
for i, v in ipairs(list) do ... end
Loop over an array in order
for k, v in pairs(t) do ... end
Loop over all keys (no guaranteed order)
while cond do ... end / repeat ... until cond
Condition loops
break / goto continue
Exit a loop / jump to a ::continue:: label

Tables

local list = {10, 20, 30}
Array — indexes start at 1
local user = {name = "Ada", age = 36}
Record / dictionary
user.name / user["name"]
Field access
table.insert(list, 40) / list[#list + 1] = 40
Append
table.remove(list, 1)
Remove by position
table.concat(list, ", ") / table.sort(list)
Join / sort in place

Functions

local function add(a, b) return a + b end
Local function
local sq = function(x) return x * x end
Anonymous function
return a, b
Multiple return values
function f(...) local n = select("#", ...) end
Variadic function
obj:method(x)
Same as obj.method(obj, x)

Metatables & OOP

setmetatable(t, mt)
Attach a metatable
mt.__index = Class
Fall back to Class for missing keys (methods)
mt.__add / __eq / __lt / __tostring / __call
Operator overloading
function Class.new(x) return setmetatable({x = x}, Class) end
Constructor

Errors & Modules

error("message")
Raise an error
local ok, err = pcall(f, arg)
Call in protected mode
assert(x, "message")
Error if x is nil or false
local M = {} ... return M
Module file pattern
local utils = require("utils")
Load a module (cached after first load)

Coroutines

local co = coroutine.create(f)
Create a coroutine
coroutine.resume(co, ...)
Start or continue it
coroutine.yield(value)
Pause and hand a value back
coroutine.wrap(f)
Coroutine as a callable generator