Lua Documentation
A tiny, fast scripting language embedded in games (Roblox), editors (Neovim) and apps.
Lua is a tiny, fast, embeddable scripting language. The whole interpreter is a few hundred kilobytes, so applications embed it to let users script them: Roblox (Luau), game engines (LÖVE, Defold), Neovim configs, Redis scripts, Nginx/OpenResty, Wireshark and more. Its single data structure — the table — does the job of arrays, dictionaries, objects and modules.
1. Introduction & Installation
- Windows: download binaries from LuaBinaries or use
scoop install lua. - macOS / Linux:
brew install lua/sudo apt install lua5.4. - Try it online at lua.org/demo.html. Package manager: LuaRocks.
lua -v
lua hello.lua # run a script
lua # interactive prompt (Ctrl + C or os.exit() to quit)
print("Hello, Codify!")
Output:
Hello, Codify!
⚠️ Common error: on Windows the executable may be called
lua54.exe— rename it tolua.exeor call it by its name.
2. Basic Syntax
- No semicolons or braces — blocks end with
end. - Comments:
-- single lineand--[[ multi-line ]]. - Variables are global by default — always use
local. ..joins strings;#gives the length of a string or array.
local name = "Asha"
local age = 20
print("Hi " .. name .. ", next year you'll be " .. age + 1)
print(#name, string.format("%s is %d years old", name, age))
--[[ this is
a multi-line comment ]]
Output:
Hi Asha, next year you'll be 21
4 Asha is 20 years old
print separates multiple values with a tab.
⚠️ Common error: a typo in a variable name silently creates a new global equal to
nil(e.g.prnit(x)→ attempt to call a nil value (global 'prnit')).
3. Variables & Data Types
Lua has eight types: nil, boolean, number (integers and floats), string, table, function, userdata and thread (coroutines).
local count = 10
local price = 99.5
local title = "Lua"
local active = true
local nothing = nil
local list = {1, 2, 3}
print(type(count), type(price), type(title), type(active), type(nothing), type(list), type(print))
print(math.type(count), math.type(price))
print(7 / 2, 7 // 2, 7 % 3, 2 ^ 10)
print(tonumber("42") + 1, tostring(10) .. "!", #tostring(12345))
print(nothing == nil, 0 and "0 is truthy" or "0 is falsy")
Output:
number number string boolean nil table function
integer float
3.5 3 1 1024.0
43 10! 5
true 0 is truthy
⚠️ Common error: only
nilandfalseare falsy —0and""are true in Lua.
4. Operators
| Category | Operators |
|---|---|
| Arithmetic | + - * / (float division) // (floor division) % ^ (power, float) |
| Comparison | == ~= (not equal!) < > <= >= |
| Logical | and or not (return one of their operands) |
| String | .. (concatenation), # (length) |
| Bitwise (5.3+) | `& |
print(10 ~= 5, not true, nil or "default", false and "x")
local x = 5
local size = (x > 3) and "big" or "small" -- Lua's ternary idiom
print(size, 6 & 3, 6 | 3, 6 ~ 3, 1 << 4)
print("con" .. "cat" .. 123)
Output:
true false default false
big 2 7 5 16
concat123
⚠️ Common error: writing
!=— Lua uses~=for "not equal".
5. Conditional Statements
local marks = 82
if marks >= 90 then
print("A")
elseif marks >= 75 then
print("B")
else
print("C")
end
local function sign(n)
if n > 0 then return "positive"
elseif n < 0 then return "negative"
end
return "zero"
end
print(sign(-4), sign(0))
-- there is no switch: use a lookup table
local actions = {
start = function() return "Starting" end,
stop = function() return "Stopping" end,
}
local cmd = "stop"
print((actions[cmd] or function() return "Unknown" end)())
Output:
B
negative zero
Stopping
6. Loops
for i = 1, 5 do io.write(i, " ") end
print()
for i = 10, 1, -3 do io.write(i, " ") end
print()
local fruits = {"apple", "mango", "kiwi"}
for index, fruit in ipairs(fruits) do -- arrays, in order
print(index, fruit)
end
local n = 1
while n < 100 do n = n * 3 end
print("n =", n)
local k = 0
repeat k = k + 1 until k >= 3
print("k =", k)
for i = 1, 10 do
if i % 2 == 0 then goto continue end -- Lua has no "continue"
if i > 7 then break end
io.write(i, " ")
::continue::
end
print()
Output:
1 2 3 4 5
10 7 4 1
1 apple
2 mango
3 kiwi
n = 243
k = 3
1 3 5 7
⚠️ Common error: arrays start at index 1 in Lua, not 0.
fruits[0]isnil.
7. Functions
Functions are first-class values. They can return multiple values and capture variables (closures).
local function add(a, b) return a + b end
local function divmod(a, b)
return a // b, a % b -- multiple return values
end
local function sum(...) -- variadic
local total = 0
for _, v in ipairs({...}) do total = total + v end
return total
end
local function greet(name, greeting)
greeting = greeting or "Hello" -- default value idiom
return greeting .. ", " .. name .. "!"
end
local function counter()
local c = 0
return function() c = c + 1; return c end -- closure
end
local q, r = divmod(17, 5)
local next = counter()
next()
print(add(2, 3), q, r, sum(1, 2, 3, 4), next())
print(greet("Asha"), greet("Ravi", "Namaste"))
local nums = {5, 2, 8, 1}
table.sort(nums, function(a, b) return a > b end) -- function as an argument
print(table.concat(nums, ","))
Output:
5 3 2 10 2
Hello, Asha! Namaste, Ravi!
8,5,2,1
8. Tables (Arrays & Dictionaries)
local nums = {10, 20, 30}
table.insert(nums, 40) -- append
table.insert(nums, 1, 5) -- insert at position 1
local removed = table.remove(nums) -- remove last
print(#nums, table.concat(nums, " "), removed)
local student = {name = "Neha", city = "Pune", marks = 85}
student.email = "neha@example.com"
student.city = nil -- delete a key
print(student.name, student["marks"], student.city)
local keys = {}
for k in pairs(student) do keys[#keys + 1] = k end -- pairs: any order
table.sort(keys)
print(table.concat(keys, ","))
local grid = {}
for r = 1, 2 do
grid[r] = {}
for c = 1, 3 do grid[r][c] = r * c end
end
print(grid[2][3])
local counts = {}
for word in ("to be or not to be"):gmatch("%a+") do
counts[word] = (counts[word] or 0) + 1
end
print(counts.to, counts.be, counts["not"])
Output:
4 5 10 20 30 40
Neha 85 nil
email,marks,name
6
2 2 1
Strings come with a library: string.upper, sub, find, gsub, rep, format, and Lua patterns (%d digits, %a letters, %s spaces):
local s = "Codify 2026 docs"
print(s:upper(), s:sub(1, 6), s:len())
print(s:find("2026"), s:match("%d+"), (s:gsub("o", "0")))
CODIFY 2026 DOCS Codify 16
8 2026 C0dify 2026 d0cs
s:find returns two values (start and end: 8, 11), but only the last argument of a call expands to all its values — in the middle of a list it is cut to the first one. Wrap a call in parentheses, like (s:gsub(...)), to keep just its first value on purpose.
⚠️ Common error:
#tis unreliable for tables with holes (nilin the middle). Keep arrays without gaps.
9. Object-Oriented Programming
Lua has no classes, but metatables let tables share behaviour like objects.
local Account = {}
Account.__index = Account -- look up missing keys in Account
function Account.new(owner, balance)
local self = setmetatable({}, Account)
self.owner = owner
self.balance = balance or 0
return self
end
function Account:deposit(amount) -- ":" passes self automatically
assert(amount > 0, "amount must be positive")
self.balance = self.balance + amount
end
function Account:__tostring() return self.owner .. ": " .. self.balance end
Account.__tostring = Account.__tostring
-- inheritance
local Savings = setmetatable({}, {__index = Account})
Savings.__index = Savings
Savings.__tostring = Account.__tostring
function Savings.new(owner, balance, rate)
local self = Account.new(owner, balance)
self.rate = rate
return setmetatable(self, Savings)
end
function Savings:addInterest() self:deposit(self.balance * self.rate) end
local s = Savings.new("Asha", 1000, 0.05)
s:deposit(1000)
s:addInterest()
print(tostring(s))
Output:
Asha: 2100.0
Metamethods customise operators: __add, __eq, __lt, __len, __call, __index, __newindex, __tostring.
⚠️ Common error: calling a method with
.instead of:—s.deposit(100)passes100asselfand fails. Uses:deposit(100).
10. Advanced Concepts
Error handling with pcall (protected call) and error:
local function divide(a, b)
if b == 0 then error("division by zero", 2) end
return a / b
end
local ok, result = pcall(divide, 10, 2)
print(ok, result)
ok, result = pcall(divide, 1, 0)
print(ok, result:match("division by zero"))
true 5.0
false division by zero
Coroutines — functions that pause (yield) and resume later, great for game logic and generators:
local gen = coroutine.wrap(function()
for i = 1, 3 do coroutine.yield(i * 10) end
end)
print(gen(), gen(), gen())
10 20 30
Modules — a file returns a table:
-- mathx.lua
local M = {}
function M.square(x) return x * x end
return M
-- main.lua
local mathx = require("mathx")
print(mathx.square(9))
Where Lua is used
-- Neovim (init.lua)
vim.opt.number = true
vim.keymap.set("n", "<leader>w", ":w<CR>")
-- Roblox (Luau)
local part = Instance.new("Part")
part.Parent = workspace
part.Touched:Connect(function(hit) print(hit.Name .. " touched the part") end)
-- Redis (atomic script): EVAL "return redis.call('INCR', KEYS[1])" 1 counter
11. Examples with Output
Example 1 — Reverse words in a sentence
local words = {}
for w in ("learn lua with codify"):gmatch("%S+") do table.insert(words, 1, w) end
print(table.concat(words, " "))
codify with lua learn
Example 2 — Fibonacci with memoization
local memo = {}
local function fib(n)
if n <= 2 then return 1 end
if memo[n] then return memo[n] end
memo[n] = fib(n - 1) + fib(n - 2)
return memo[n]
end
print(fib(50))
12586269025
Example 3 — Filter and map helpers
local function filter(t, f) local r = {} for _, v in ipairs(t) do if f(v) then r[#r + 1] = v end end return r end
local function map(t, f) local r = {} for i, v in ipairs(t) do r[i] = f(v) end return r end
local evens = filter({1, 2, 3, 4, 5, 6}, function(x) return x % 2 == 0 end)
print(table.concat(map(evens, function(x) return x * x end), " "))
4 16 36
12. Practice Problems
- Print all prime numbers below 50.
- Count vowels in a string using
gsub(it returns the number of replacements). - Write
split(str, sep)that returns a table of parts. - Implement a
Stack"class" withpush,popandpeekusing metatables. - Create a
Vectortype with__addand__tostringmetamethods. - Write a coroutine-based generator that yields the Fibonacci sequence.
- Configure Neovim with Lua: line numbers, a colour scheme and two key mappings.
- Make a small LÖVE (
love2d) game: a square that moves with the arrow keys.
13. Interview Questions
1. What makes Lua popular for embedding? It's tiny, fast, written in portable C, has a simple C API and clean syntax — easy to add scripting to games and applications.
2. What is a table? Lua's only data structure — an associative array that can act as an array, dictionary, object, module or namespace.
3. Why do Lua arrays start at 1?
By convention: the standard library (ipairs, #, table.insert) treats sequences as starting at 1.
4. pairs vs ipairs?
ipairs iterates array indices 1, 2, 3... in order until the first nil; pairs iterates all keys in an unspecified order.
5. What are metatables?
Tables that define custom behaviour for another table — operator overloading, default values (__index), inheritance.
6. . vs : when calling functions?
obj:method(x) is sugar for obj.method(obj, x) — it passes the object as self.
7. How does error handling work?
error() raises an error; pcall/xpcall call a function in protected mode and return false plus the message on failure.
8. What are coroutines?
Cooperative threads: a coroutine runs until it yields, and resumes later where it left off — no parallelism, but great for sequencing.
9. Why use local?
Globals are slower and risk name clashes; locals are faster (registers) and limited to their block.
10. What is LuaJIT / Luau? LuaJIT is a very fast just-in-time compiler for Lua 5.1; Luau is Roblox's typed, sandboxed Lua dialect.
14. Cheat Sheet & References
Basics
-- output, variables, strings
print("Hi", name); io.write("no newline")
local x = 5; local s = "a" .. "b"; local n = #s
local num = tonumber("42"); local str = tostring(42)
local v = cond and a or b
Control flow
if a then elseif b then else end
for i = 1, 10, 2 do end
for i, v in ipairs(arr) do end
for k, v in pairs(tbl) do end
while cond do end; repeat until cond
Tables
local t = {1, 2, 3}; t[#t + 1] = 4; table.insert(t, 1, 0); table.remove(t)
local d = {name = "Asha"}; d.age = 20; d["city"] = "Pune"; d.age = nil
table.sort(t, function(a, b) return a > b end); table.concat(t, ",")
Strings
s:upper(); s:lower(); s:sub(1, 3); s:len(); s:rep(3)
s:find("x"); s:match("%d+"); s:gsub("a", "b"); s:gmatch("%a+")
string.format("%s has %d points (%.1f%%)", name, n, pct)
Functions and OOP
local function f(a, b, ...) return a + b end
local Cls = {}; Cls.__index = Cls
function Cls.new(x) return setmetatable({x = x}, Cls) end
function Cls:get() return self.x end
Errors and coroutines
local ok, err = pcall(fn, arg)
error("message"); assert(x > 0, "x must be positive")
local co = coroutine.create(fn); coroutine.resume(co); coroutine.yield(v)
local M = require("module")
Official documentation