Lua Cheatsheet

Strings and Patterns

Use this Lua reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

String Literals

local a = 'single quotes'
local b = "double quotes"
local c = [[long string
can span lines]]

Escape examples: \n, \t, \\, \", \'.

Common Methods

local s = "  Lua Language  "
s:lower()          -- "  lua language  "
s:upper()          -- "  LUA LANGUAGE  "
s:sub(3, 5)        -- substring, inclusive indexes
s:rep(3)           -- repeat
s:reverse()        -- reversed bytes/chars
s:find("Lua")      -- start, end or nil
s:gsub("Lua", "Plain Lua")

Colon calls pass the string as the first argument: s:upper() equals string.upper(s).

Byte and Char

string.byte("ABC", 1)    -- 65
string.char(65, 66, 67)  -- "ABC"

Formatting

string.format("%s scored %d", "Ada", 98)
string.format("%.2f", 3.14159)    -- "3.14"
string.format("%04d", 7)          -- "0007"

Patterns Overview

Lua patterns are smaller than regular expressions.

PatternMeaning
.any character
%aletter
%ddigit
%swhitespace
%Snon-whitespace
%walphanumeric
%ppunctuation
%llowercase letter
%uuppercase letter
+one or more
*zero or more
-zero or more, non-greedy
?optional
%bxybalanced pair, e.g. %b() matches (...) with nesting
%f[set]frontier: empty match where text transitions into set

Pattern Examples

for word in text:gmatch("%S+") do print(word) end
local digits = text:match("%d+")
local clean = text:gsub("%s+", " ")
local key, value = line:match("^(%w+)%s*=%s*(.+)$")
local parens = text:match("%b()")          -- "(a (nested) group)"
local n = select(2, text:gsub("%f[%w]%w+", ""))  -- word count via frontier

Escaping Pattern Magic

Use % to escape magic characters: ( ) . % + - * ? [ ^ $.

local literal_dot = text:find("%.")
local percent = text:find("%%")

Simple Trim

local function trim(s)
  return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end

Or with capture:

local function trim(s)
  return s:match("^%s*(.-)%s*$")
end

UTF-8 (Lua 5.3+)

Lua strings are byte sequences: #s, s:sub, and patterns all count bytes. The utf8 library works in code points.

utf8.len("héllo")            -- 5 code points (nil + byte pos on invalid UTF-8)
print(#"héllo")              -- 6 bytes
utf8.char(72, 105, 0x203D)   -- "Hi‽" (code points to string)
utf8.codepoint("é")          -- 233
for pos, code in utf8.codes("héllo") do
  print(pos, code)           -- byte offset, code point
end
utf8.charpattern             -- pattern matching one UTF-8 byte sequence

Not available on Lua 5.1/5.2 or stock LuaJIT — use a library such as luautf8 there.