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
Cookies & your privacy
We use essential cookies to keep this site working and secure.
With your permission, we'd also like to use Google Analytics cookies to understand site traffic.
We don't use advertising or social media tracking cookies, and we honor Global Privacy Control (GPC) browser signals.
Learn more in our Privacy Policy.
Your browser is sending a GPC signal, so analytics stays off even if you accept.