Menu

Lua Cheat Sheet

Last updated

Hello World & running code

Lua is minimal - a single statement runs.

OperationSyntax
Print a lineprint("Hello, World!")
Print multiple valuesprint("x", 1, true)
Write without newlineio.write("Hi")
Comment-- this is a comment
Multi-line comment--[[ ... ]]
Concatenate stringsprint("Hi " .. name)
Run a filelua app.lua
Interactive shelllua

Variables & types

Variables are global by default; declare locals with local.

OperationSyntax
Local variablelocal age = 30
Global variablecount = 0
Multiple assignmentlocal a, b = 1, 2
The eight typesnil, boolean, number, string, table, function, userdata, thread
Nil / booleansnil, true, false
Check typetype(x) returns "number"
Convert to numbertonumber("42")
Convert to stringtostring(42)

Strings

Strings are immutable; both single and double quotes work.

OperationSyntax
Length#s or string.len(s)
Concatenates1 .. s2
Uppercase / lowercases:upper(), s:lower()
Substrings:sub(1, 3)
Find substrings:find("ell")
Replace (gsub)s:gsub("a", "b")
Formatstring.format("%05d", 42)
Long string[[ multi\nline ]]

Tables (the core data structure)

Tables are Lua's only structured type - they act as arrays, maps, and objects.

OperationSyntax
Empty tablelocal t = {}
Array-style (1-based)local t = {10, 20, 30}
Access array elementt[1] (first element)
Map-style tablelocal u = {name = "Ada", age = 30}
Access map valueu.name or u["name"]
Set a valuet[4] = 40, u.email = "a@x.com"
Length of array part#t
Iterate array (ipairs)for i, v in ipairs(t) do ... end
Iterate all keys (pairs)for k, v in pairs(u) do ... end
Nested tablelocal m = {a = {1, 2}}

Control flow

Blocks close with end; only nil and false are falsy.

OperationSyntax
If / elseif / elseif x > 0 then ... elseif x < 0 then ... else ... end
Logical operatorsand, or, not
Numeric forfor i = 1, 10 do ... end
For with stepfor i = 10, 1, -1 do ... end
While loopwhile x < 100 do ... end
Repeat-untilrepeat ... until done
Breakbreak
Not-equal operatorif a ~= b then ... end

Functions

Functions are first-class values and can return multiple results.

OperationSyntax
Define a functionfunction add(a, b) return a + b end
Local functionlocal function square(x) return x * x end
Anonymous functionlocal f = function(x) return x * 2 end
Multiple return valuesfunction bounds() return 1, 10 end
Capture multiple returnslocal lo, hi = bounds()
Variadic functionfunction sum(...) ... end
Collect varargslocal args = {...}
Method (colon syntax)function obj:greet() ... end

String library

Common functions from the string library (callable as s:fn()).

FunctionWhat it does
string.len(s)Length of the string
string.sub(s, i, j)Substring from index i to j
string.upper(s)Uppercase copy
string.rep(s, n)Repeat the string n times
string.find(s, p)Find a pattern, returns start/end
string.match(s, p)Return first pattern match
string.gsub(s, p, r)Replace all pattern matches
string.format(fmt, ...)Format values into a string

Table & math libraries

Helpers for working with array-style tables and numbers.

FunctionWhat it does
table.insert(t, v)Append a value to the end
table.insert(t, i, v)Insert v at position i
table.remove(t, i)Remove and return element at i
table.concat(t, ", ")Join elements into a string
table.sort(t)Sort the array in place
math.floor(x) / math.ceil(x)Round down / up
math.max(...) / math.min(...)Largest / smallest argument
math.random(1, 6)Random integer in a range

Metatables (brief)

Metatables let you customize how tables behave - operators, indexing, and more.

OperationSyntax
Set a metatablesetmetatable(t, mt)
Get a metatablegetmetatable(t)
Fallback for missing keysmt.__index = defaults
Default via functionmt.__index = function(t, k) ... end
Customize additionmt.__add = function(a, b) ... end
Customize tostringmt.__tostring = function(t) ... end
Prototype-based OOPmt.__index = ClassTable

The Lua syntax you reach for most, on one page. This Lua cheat sheet is a quick reference for the core language - variables and types, strings, control flow, functions, and the tables that serve as Lua's single, flexible data structure, plus a peek at the standard libraries and metatables.

Everything here is standard Lua and runs on a stock interpreter. Copy what you need, or try every snippet live in the Lua playground - no install required.

Lua cheat sheet FAQ

Is this Lua cheat sheet free?
Yes. This Lua cheat sheet is completely free, with no sign-up required. Bookmark it and come back whenever you need to look up a table operation, string function, or control-flow keyword.
How can a Lua table be both an array and a map?
A table is just a set of key-value pairs, and the key can be any value. When you use consecutive integer keys starting at 1 ({10, 20, 30}) the table behaves like an array; when you use string keys ({name = "Ada"}) it behaves like a map. You can even mix both in the same table. This is why Lua only needs one structured type - the table covers arrays, dictionaries, sets, and objects.
Why does Lua use 1-based indexing?
By convention and design, Lua arrays start at index 1, not 0 - so t[1] is the first element and #t is the count. The length operator # and library functions like table.insert and ipairs all assume this 1-based convention, so sticking to it keeps your array code working as expected.
Can I practice Lua online?
Yes. Open the Lua playground to run any snippet from this cheat sheet in your browser - no Lua install needed. When you want structure, Coddy's free interactive Lua course takes you from variables and tables to functions and metatables step by step.
Is this cheat sheet good for beginners?
Yes. It is organized from the most common topics (variables, strings, tables, control flow) down to advanced ones (the standard libraries and metatables), so you can use the top sections on day one and grow into the rest.
Coddy programming languages illustration

Learn Lua with Coddy

GET STARTED