Why this matters
Lua is small by design. The entire language fits in a short manual, the interpreter is only a few hundred kilobytes, and it starts almost instantly. That is why it is embedded in games, applications, routers, and databases as a scripting layer. A host program can expose a few functions, and Lua scripts can then drive behavior that would otherwise require a rebuild.
Learning Lua teaches you how much you can do with a handful of powerful ideas. Tables serve as arrays, maps, objects, and modules. Functions are ordinary values you can store, pass, and return. It is a language that trusts the programmer and stays out of the way, so the distance between an idea and working code is very short.
Its function system is especially elegant. Functions are first-class, closures capture their surroundings naturally, multiple returns remove the need for out parameters, and varargs let you write flexible interfaces. The colon syntax gives you object-like methods with almost no machinery, and coroutines offer a lightweight form of cooperative concurrency. These features pack a lot of expressive power into a very small language.
The big picture
Lua has very few moving parts. There are values, which can be numbers, strings, booleans, nil, functions, tables, and threads; and there are functions that manipulate them. Tables are the single general-purpose data structure, built from key-value pairs, and they can represent nearly anything. Functions are values too, which means you can treat behavior exactly like data.
A Lua script is a sequence of statements executed from top to bottom by the interpreter. The language is dynamically typed, so variables have no declared type and a value carries its own type with it. There is no compile step in the usual sense, which makes iteration fast: edit a script and run it again immediately.
Functions in Lua are created with the function keyword or as expressions, and they can be anonymous. Because a function is a value, closures are natural: a function can refer to local variables from the scope where it was created, and those variables stay alive as long as the function does. Coroutines add another dimension, letting a function pause and resume cooperatively.
Core ideas
Function declarations
You declare a named Lua function with the function keyword, its name, a parenthesized parameter list, and an end keyword to close the body. Unlike many languages, Lua uses the word end rather than braces, and there are no semicolons to worry about. Indentation is purely for people reading the code.
Functions do not have to be declared before use in any strict sense as long as the assignment has happened by the time the call executes. In practice you define helpers before the code that calls them. A function stored in a local variable is limited to that block, which is a good habit for keeping names tidy.
function greet(name)
print("Hello, " .. name)
end
greet("Ada")
Watch out. Forgetting the end keyword. Lua uses end to close functions and control blocks, and missing one produces a syntax error pointing near the end of the file.
Functions as first-class values
In Lua a function is an ordinary value. You can store it in a variable, put it in a table, pass it as an argument, and return it from another function. The syntax function(x) return x * 2 end creates an anonymous function expression, and assigning it to a name is equivalent to a named declaration.
This first-class status is the foundation of higher-order programming in Lua. Standard library calls such as table.sort accept a comparison function, and you can supply a small anonymous function right there. Being able to pass behavior around makes code compact and highly reusable.
local double = function(x)
return x * 2
end
print(double(21))
Watch out. Confusing function f() ... end with a call. The declaration creates a value; you call it separately with f(). Parentheses matter.
Parameters and arguments
Parameters are listed in parentheses after the function name. When there are fewer arguments than parameters, the missing parameters receive nil. When there are more arguments than parameters, the extras are simply ignored unless the function collects them with varargs. Lua never complains about a mismatch at call time.
This flexibility is convenient but means you should document what a function expects. Checks are usually written explicitly, for example testing whether a parameter is nil or of the expected type. Because dynamic typing shifts some checks to runtime, clear parameter names and small guard clauses go a long way.
function describe(name, age)
if age == nil then
age = "unknown"
end
print(name .. " is " .. age)
end
Watch out. Assuming a missing argument becomes an empty string or zero. It becomes nil, and concatenating nil with a string raises an error, so supply a default explicitly.
Multiple returns
A Lua function can return several values at once by separating them with commas after the return keyword. The caller can receive them in multiple variables, which removes the need for awkward out parameters or wrapper tables. This is one of the language's most pleasant features.
Lua adjusts the number of returned values to fit the context. In a single-value context, such as an arithmetic expression, only the first value is kept. In a multi-value context, such as a list of assignments or arguments to another function, all values survive. Learning these adjustment rules explains a lot of seemingly surprising behavior.
function minmax(a, b)
if a < b then
return a, b
else
return b, a
end
end
local lo, hi = minmax(7, 3)
Watch out. Placing a multi-return call in the middle of an argument list. Lua keeps only the first value unless the call is the final argument, so reorder calls or wrap them in parentheses.
Varargs with three dots
A function can accept a variable number of arguments by ending its parameter list with three dots. Inside the body, the same three dots stand for those extra values. This is how you write functions like a sum helper that works with any number of inputs, without naming each parameter.
If you need to inspect or reuse the arguments more than once, pack them into a table with the standard function table.pack, or iterate with select and an index. Varargs are evaluated fresh at each use, so repeatedly referring to the dots is fine but converting them to a table is often clearer for complex logic.
function sum(...)
local total = 0
for _, value in ipairs({...}) do
total = total + value
end
return total
end
Watch out. Using varargs inside a nested function and expecting them to refer to the outer call. The three dots always belong to the innermost vararg function, so capture them in a local table first.
Closures and upvalues
A closure is a function together with the local variables it refers to from an enclosing scope. Those referenced variables are called upvalues. Even after the outer function has returned, the upvalues stay alive because the inner function still needs them, and each call to the outer function creates a fresh set.
This makes closures ideal for creating functions with private state. A counter factory can define a local count, return an inner function that increments and returns it, and every generated counter keeps its own independent count. No global variables and no special object syntax are required.
function make_counter()
local count = 0
return function()
count = count + 1
return count
end
end
local next = make_counter()
Watch out. Sharing a single loop variable among several closures by mistake. Declare a fresh local inside the loop so each closure captures its own value rather than the final loop value.
Methods and colon syntax
Lua does not have classes, but tables can hold functions and that is enough to build object-like code. The colon syntax is shorthand for calling a function stored in a table and passing the table itself as the first argument. That hidden first argument is conventionally named self.
Defining function Account:deposit(amount) is the same as defining Account.deposit = function(self, amount). Calling account:deposit(10) passes account as self automatically. This small piece of sugar makes methods read naturally while keeping the underlying model simple: just tables and functions.
local account = { balance = 0 }
function account:deposit(amount)
self.balance = self.balance + amount
end
account:deposit(50)
Watch out. Mixing dot and colon syntax. Using a dot to call a method defined with a colon leaves out self, so the function receives the wrong arguments. Match the two consistently.
Recursion
A recursive Lua function calls itself to solve a smaller instance of a problem. You need a base case that stops the recursion, otherwise the calls continue until the interpreter runs out of stack space. Local recursive functions need to be declared with local before assignment, so the name is visible inside the body.
Recursion is a natural fit for nested structures such as trees and for mathematical definitions like factorial. Because Lua is dynamically typed and interprets code, deep recursion can be slower than an iterative loop, so use it where the structure of the problem genuinely calls for it.
local function factorial(n)
if n <= 1 then
return 1
end
return n * factorial(n - 1)
end
print(factorial(5))
Watch out. Writing local factorial = function(n) ... factorial(...) end. The name is not yet in scope inside its own expression, so use the local function form instead.
Coroutines briefly
A coroutine is a function that can pause execution and resume later. You create one with coroutine.create and a function, start or continue it with coroutine.resume, and pause inside it with coroutine.yield. Values passed between resume and yield let the two sides exchange data.
Coroutines are cooperative, meaning one runs only until it yields or finishes. They are useful for generators, state machines, and walking trees without keeping an explicit stack. They are not parallel threads, so they do not make code run faster, but they can make certain control flows much easier to express.
local co = coroutine.create(function()
for i = 1, 3 do
coroutine.yield(i)
end
end)
print(coroutine.resume(co))
print(coroutine.resume(co))
Watch out. Treating coroutines as parallel threads. Only one coroutine runs at a time, and it yields control explicitly, so long work inside one still blocks everything else.
Functions
Functions are the main tool Lua gives you for organizing behavior, and because they are values, they appear everywhere. You pass them to library functions, store them in tables as methods, return them from factories as closures, and pause them as coroutines. Understanding functions thoroughly is most of understanding Lua.
This section looks at the details that make Lua functions distinctive. You will see how argument and return adjustment works, how closures capture upvalues, how colon syntax hides the self parameter, and where coroutines fit. Each idea is small on its own but very powerful in combination.
Functions as values
A named declaration in Lua is really an assignment of a function value to a variable. The long form function f() ... end is shorthand for f = function() ... end. Once you internalize that, the rest of the language falls into place, because every place a value is allowed is a place a function can go.
Storing functions in tables gives you dispatch tables and simple objects. Passing functions as arguments gives you callbacks and higher-order helpers. Returning them gives you factories and closures. The same single concept supports all of these patterns without any extra syntax.
local operations = {
add = function(a, b) return a + b end,
mul = function(a, b) return a * b end
}
print(operations.add(2, 3))
Parameters and extra arguments
Lua matches arguments to parameters from left to right. Extra arguments are discarded unless the function ends its parameter list with varargs, and missing parameters become nil. There is no arity check, so the function itself is responsible for validating what it needs.
This design makes calls lightweight and flexible, and it is a big part of why Lua is pleasant for scripting. It also means that mistakes surface as runtime errors rather than compile-time complaints, so small guard clauses at the top of important functions are a wise investment.
function greet(first, last)
last = last or "friend"
print("Hi " .. first .. " " .. last)
end
Multiple returns and adjustment
A return statement can list several expressions, and all of them flow back to the caller. When the call appears alone or in a list of assignments, all values are used. When it appears where a single value is required, Lua keeps only the first, silently discarding the rest.
Wrapping a call in parentheses forces a single result, which is useful when you want to be explicit. Conversely, placing a multi-return call as the final item in another call forwards all its values as arguments. These rules explain how functions like pcall and unpack compose so neatly.
function pair()
return 10, 20
end
local a, b = pair()
local only = (pair())
Varargs in practice
Three dots in the parameter list collect any number of extra arguments. Inside the body, three dots expand to those values. To store them for repeated use, collect them into a table, since a plain list construction with the dots is the idiomatic way to capture them.
Varargs are common in utility functions and wrappers. A logging function might accept a fixed level followed by any number of messages. Pay attention to scope: the dots always refer to the current function, so a nested closure must capture them into a local table if it needs them later.
function log(level, ...)
local parts = {...}
print(level .. ": " .. table.concat(parts, " "))
end
Closures and upvalues
When a function refers to a local from an outer scope, that local becomes an upvalue captured by the closure. The variable itself is captured, not a copy of its value, so changes are visible to the closure. Each invocation of the outer function produces a new, independent upvalue.
Closures are the basis of iteration helpers, stateful callbacks, and simple encapsulation. A factory function can hide a local variable completely, exposing only the inner function that manipulates it. That gives you private state without any dedicated syntax for privacy.
function new_accumulator(start)
local total = start
return function(delta)
total = total + delta
return total
end
end
Methods and self
Colon syntax is a convenience for calling functions stored in tables. Defining with a colon adds a hidden self parameter, and calling with a colon inserts the table as that first argument. The result is methods that look and feel like those in class-based languages, even though Lua has no classes.
You can still use dot syntax when you want to pass the receiver explicitly or call the function without one. Mixing the two accidentally is a frequent source of bugs, so once you define a method with a colon, call it with a colon unless you have a specific reason not to.
local counter = { n = 0 }
function counter:inc(by)
self.n = self.n + (by or 1)
return self.n
end
print(counter:inc())
Recursion and coroutines
Recursive functions work like anywhere else, but declaring local functions with the local function form ensures the name is visible inside the body. That small detail matters because a plain local assignment does not make the variable available within its own initializer.
Coroutines extend the idea of a function to one that can yield and resume. They share no automatic scheduling, so you drive them explicitly with resume. Used thoughtfully, they turn complex iterative logic into straightforward sequences that read top to bottom.
local function walk(node)
if not node then return end
print(node.value)
walk(node.left)
walk(node.right)
end
Function reference
These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.
function declaration
User-defined form
A function declaration gives a name to a reusable block of statements. In Lua, functions are first-class values, so declaring one effectively assigns a function to a variable.
| Syntax | function add(a, b) return a + b end |
|---|---|
| Parameters | a — First argument b — Second argument |
| Returns | Whatever the return statements produce; here the sum. |
function add(a, b)
return a + b
end
print(add(2, 3))
What you can do with it. Group repeated logic under a clear name Split a script into manageable pieces Define callbacks expected by other libraries
Choose it when. Choose a named declaration for logic you reuse, rather than an anonymous function when the block is used exactly once.
| Mistake | Fix |
|---|---|
| Forgetting the end keyword | Every function block must close with end, or the parser reports an error. |
| Using a global when you meant local | Write local function to avoid polluting the global namespace and clashing names. |
function expression
User-defined form
A function expression creates an anonymous function as a value. You can store it in a variable, put it in a table, or pass it straight to another function.
| Syntax | local f = function(x) return x * 2 end |
|---|---|
| Parameters | x — The function's argument |
| Returns | The value of the body's return statement. |
local double = function(x)
return x * 2
end
print(double(5))
What you can do with it. Pass a callback to table.sort Attach a handler to a table field Build higher-order helpers that take functions
Choose it when. Choose a function expression for a short inline callback, rather than a named declaration when the name adds no clarity.
| Mistake | Fix |
|---|---|
| Forgetting the end keyword | Anonymous functions still need a matching end to close the block. |
| Confusing the two syntaxes | function f() and f = function() create the same kind of value; pick whichever reads better. |
method with colon syntax
User-defined form
Colon syntax defines and calls methods with an implicit self parameter. It is Lua's sugar for an object-oriented style built on ordinary tables.
| Syntax | function Account:deposit(n) self.balance = self.balance + n end |
|---|---|
| Parameters | self — The implicit receiver table n — Amount to add |
| Returns | Whatever the body returns. |
local Account = { balance = 0 }
function Account:deposit(n)
self.balance = self.balance + n
end
Account:deposit(100)
What you can do with it. Define behavior on table-based objects Encapsulate state in a receiver Support familiar object-style method calls
Choose it when. Choose colon syntax for functions that operate on a receiver, rather than dot syntax for plain functions stored in tables.
| Mistake | Fix |
|---|---|
| Mixing dot and colon call syntax | obj:m(x) passes self automatically; obj.m(x) does not, so mind how you defined it. |
| Forgetting to use self inside the method | Refer to self.balance and other fields through the implicit receiver. |
closure/upvalue
User-defined form
A closure is a function that captures variables from the scope where it was defined. Those captured variables are called upvalues, and they stay alive as long as the closure does.
| Syntax | local function counter() local n = 0; return function() n = n + 1; return n end end |
|---|---|
| Returns | A function that reads and updates the captured upvalues. |
local function counter()
local n = 0
return function()
n = n + 1
return n
end
end
local next = counter()
print(next(), next())
What you can do with it. Build stateful iterators and generators Keep private state without globals Create callbacks that remember their context
Choose it when. Choose a closure when a function must remember state across calls, rather than a global variable that everything can touch.
| Mistake | Fix |
|---|---|
| Sharing one upvalue when you wanted separate copies | Create a fresh local inside each iteration so each closure captures its own value. |
| Expecting captured state to reset between calls | The upvalue persists; create a new closure if you want a fresh counter. |
varargs
User-defined form
Varargs let a function accept any number of extra arguments. You write ... in the parameter list and read the values with select or by packing them into a table.
| Syntax | function sum(...) local t = {...} end |
|---|---|
| Parameters | ... — A variable number of extra arguments |
| Returns | Whatever the body returns. |
function sum(...)
local total = 0
for _, v in ipairs({...}) do
total = total + v
end
return total
end
print(sum(1, 2, 3))
What you can do with it. Write functions with optional arguments Create wrapper functions that pass arguments through Can you build a simple print-like formatter
Choose it when. Choose varargs when the number of arguments genuinely varies, rather than fixed named parameters for clarity.
| Mistake | Fix |
|---|---|
| Using #{...} to count arguments | Nil holes break the length operator; use select('#', ...) for an accurate count. |
| Assuming ... is a table | It is a special expression; wrap it as {...} when you need table operations. |
multiple returns
User-defined form
A Lua function can return several values separated by commas. Lua adjusts the list to the calling context, keeping extra values or dropping them as needed.
| Syntax | function minmax(a, b) if a < b then return a, b else return b, a end end |
|---|---|
| Parameters | a — First value to compare b — Second value to compare |
| Returns | Two values here: the smaller one first, then the larger. |
function minmax(a, b)
if a < b then
return a, b
else
return b, a
end
end
local lo, hi = minmax(5, 2)
What you can do with it. Return a value together with a status flag Produce several related results at once Follow the iterator convention for generic for loops
Choose it when. Choose multiple returns for a few related results, rather than allocating a table just to bundle them.
| Mistake | Fix |
|---|---|
| Expecting extra values in a single-value context | Extra results are discarded when only one value is requested. |
| Placing a multi-return call before other list items | Only the last expression in a list expands to multiple values; wrap it to adjust. |
coroutine.create
Standard library function
coroutine.create makes a new suspended coroutine from a function and returns a handle to it. The function does not run until you resume the coroutine.
| Syntax | local co = coroutine.create(function() ... end) |
|---|---|
| Parameters | f — The function the coroutine will execute |
| Returns | A coroutine handle, a value of Lua's thread type. |
local co = coroutine.create(function()
print("step 1")
coroutine.yield()
print("step 2")
end)
What you can do with it. Set up cooperative tasks Implement generators that pause and resume Run a computation in small, controlled steps
Choose it when. Choose coroutine.create to prepare a pausable task, rather than a plain function call that must run to completion.
| Mistake | Fix |
|---|---|
| Expecting the body to run right away | A new coroutine is suspended; call coroutine.resume to start it. |
| Losing the handle | Keep the returned value, since it is the only way to control that coroutine. |
coroutine.resume
Standard library function
coroutine.resume starts or continues a coroutine until it yields or finishes. Values passed to resume become the results of the paused yield call.
| Syntax | local ok, value = coroutine.resume(co) |
|---|---|
| Parameters | co — The coroutine handle ... — Values delivered to the coroutine's yield |
| Returns | true plus any yielded values on success, or false plus an error message on failure. |
local co = coroutine.create(function()
local x = coroutine.yield(10)
print("got", x)
end)
local ok, value = coroutine.resume(co)
print(ok, value)
coroutine.resume(co, 99)
What you can do with it. Drive a coroutine from start to finish Send values back into a paused coroutine Pump values out of a generator
Choose it when. Choose resume to advance a coroutine and collect its yielded values, rather than invoking its function directly.
| Mistake | Fix |
|---|---|
| Ignoring the first ok result | Check it, because errors inside the coroutine are reported there rather than raised. |
| Resuming a coroutine that already finished | Treat a dead coroutine as unusable; create a new one to run again. |
coroutine.yield
Standard library function
coroutine.yield pauses the running coroutine and returns control to the code that called resume. Values passed to yield become extra results of that resume.
| Syntax | local received = coroutine.yield(value) |
|---|---|
| Parameters | ... — Values handed back to resume |
| Returns | Whatever values the next resume passes into the coroutine. |
local function generator()
for i = 1, 3 do
coroutine.yield(i)
end
end
local co = coroutine.create(generator)
print(coroutine.resume(co))
What you can do with it. Implement a generator that emits values one at a time Pause between steps of a long computation Build cooperative schedulers
Choose it when. Choose yield when a coroutine should pause and hand data back, rather than blocking the whole program.
| Mistake | Fix |
|---|---|
| Calling yield outside a coroutine | yield only works inside a coroutine; at top level it raises an error. |
| Confusing values sent in with values yielded out | yield's arguments go out to resume; yield's return values come from the next resume. |
Standard library function
print writes its arguments to standard output separated by tabs and followed by a newline. It converts values to strings for you, which makes it the quick way to inspect results.
| Syntax | print(a, b, c) |
|---|---|
| Parameters | ... — Any number of values to print |
| Returns | Nothing. |
print("Hello", "world")
print(1 + 2)
What you can do with it. Print debug values while experimenting Show a quick result in a script Trace values passing through a function
Choose it when. Choose print for rough, fast debugging, rather than string.format when the output needs a specific shape.
| Mistake | Fix |
|---|---|
| Expecting formatted columns | print uses tabs; use string.format or io.write when you need precise formatting. |
| Expecting a table to print its contents | Tables print as an address; write a loop or use a serializer to inspect them. |
table.insert
Standard library function
table.insert adds an element to a table used as an array, either at the end or at a position you choose, shifting later elements to make room.
| Syntax | table.insert(t, value) |
|---|---|
| Parameters | t — The table acting as an array pos — Optional insertion index, defaulting to the end value — The value to insert |
| Returns | Nothing; the table is modified in place. |
local t = {"b", "c"}
table.insert(t, 1, "a")
table.insert(t, "d")
print(table.concat(t, ", "))
What you can do with it. Build a list one item at a time Insert an element at a specific index Gather results inside a loop
Choose it when. Choose table.insert for ordered arrays, rather than t[#t + 1] = value when you want the direct assignment instead.
| Mistake | Fix |
|---|---|
| Inserting past the end of the array | Use a position no greater than #t + 1, or just append without a position. |
| Using sparse tables with holes | Keep sequence indices contiguous, because length and array functions rely on that. |
table.concat
Standard library function
table.concat joins the array portion of a table into one string, with an optional separator and slice. Its elements must be strings or numbers.
| Syntax | table.concat(t, ", ") |
|---|---|
| Parameters | t — Array of strings or numbers sep — Optional separator placed between items i, j — Optional start and end indices |
| Returns | A single string made by joining the chosen elements. |
local words = {"red", "green", "blue"}
print(table.concat(words, ", "))
What you can do with it. Join words into a sentence Build CSV or other delimited lines Serialize a simple list of values
Choose it when. Choose table.concat to join an array efficiently, rather than a loop that repeatedly grows a string.
| Mistake | Fix |
|---|---|
| Leaving a nil inside the range | Nil elements are not accepted; fill the holes or choose a valid slice. |
| Assuming arbitrary types are allowed | Only strings and numbers concatenate; convert other values first. |
string.format
Standard library function
string.format builds a string from a format string and a list of values, following C printf-style placeholders such as %d, %s, and %.2f.
| Syntax | string.format("%s: %d", name, n) |
|---|---|
| Parameters | format — A string containing % placeholders ... — Values that fill the placeholders in order |
| Returns | The formatted string. |
local name, n = "Ana", 3
print(string.format("%s has %d items", name, n))
print(string.format("%.2f", 3.14159))
What you can do with it. Produce aligned report columns Control decimal precision Build consistent log and error messages
Choose it when. Choose string.format for precise, predictable formatting, rather than print's simple tab separation.
| Mistake | Fix |
|---|---|
| Mismatching a placeholder and its value's type | Use %d for integers, %s for strings, and %f for floats; a mismatch raises an error. |
| Forgetting to escape a literal percent sign | Write %% when you want a single % in the output. |
ipairs
Standard library function
ipairs returns an iterator that walks a table's array part in numeric order from 1 until the first nil. It is the usual way to loop over a sequence.
| Syntax | for i, v in ipairs(t) do ... end |
|---|---|
| Parameters | t — The table whose array part you want to traverse |
| Returns | An iterator triple for use in a generic for loop. |
local fruits = {"apple", "banana", "cherry"}
for i, fruit in ipairs(fruits) do
print(i, fruit)
end
What you can do with it. Loop over array elements in order Get both the index and the value Process a sequence until its end
Choose it when. Choose ipairs for ordered traversal of a sequence, rather than pairs for all entries of a general table.
| Mistake | Fix |
|---|---|
| Expecting it to visit non-array keys | ipairs ignores string keys; use pairs when you need every key-value entry. |
| Having a nil gap in the sequence | ipairs stops at the first nil, so keep array indices contiguous. |
Common mistakes here
| Mistake | Fix |
|---|---|
| Forgetting the end that closes a function | Count your function and if blocks, and close each one with an end keyword. |
| Calling a colon method with a dot, leaving out self | Define and call consistently with the colon so the receiver is passed automatically. |
| Assuming a missing argument is zero or an empty string | It is nil; supply a default with the or operator or check explicitly. |
| Losing extra return values in a single-value context | Capture all results in a variable list, or make the multi-return call the last argument. |
| Expecting coroutines to run in parallel | Remember they are cooperative; one runs until it explicitly yields control. |
The example, line by line
This small Lua program defines a recursive function and uses it to compute a value.
| Code | What it does |
|---|---|
1local function factorial(n) | Declares a local recursive function named factorial with one parameter. |
2 if n <= 1 then | Tests the base case, stopping when n has reached one or less. |
3 return 1 | Returns one for the base case, ending that branch of recursion. |
4 end | Closes the if block with end, as Lua requires. |
5 return n * factorial(n - 1) | Otherwise multiplies n by a recursive call with a smaller value. |
6end | Closes the function body with end. |
7local result = factorial(5) | Calls factorial with five and stores the result in a local variable. |
8print("Factorial: " .. result) | Converts the number to text with concatenation and prints the answer. |
local function factorial(n)
if n <= 1 then
return 1
end
return n * factorial(n - 1)
end
local result = factorial(5)
print("Factorial: " .. result)
Worked variations
A closure with private state
This factory returns a function that remembers its own total. The local variable is an upvalue captured by the closure, and each call to the factory produces an independent counter. Nothing global is involved, so the state is effectively private.
function make_counter()
local count = 0
return function()
count = count + 1
return count
end
end
local a = make_counter()
local b = make_counter()
print(a(), a(), b())
A table method with colon syntax
Here a table holds both data and a method. The colon hides the self parameter on definition and inserts the receiver on the call, so deposit can update the correct balance. This is the standard way to write object-like code in Lua.
local wallet = { funds = 0 }
function wallet:deposit(amount)
self.funds = self.funds + amount
end
function wallet:total()
return self.funds
end
wallet:deposit(25)
print(wallet:total())
A generator with coroutines
This coroutine yields successive values from a loop, acting like a simple generator. Each resume runs the function until the next yield, and the values passed back let the caller consume one item at a time without building a full list.
local function range(n)
return coroutine.create(function()
for i = 1, n do
coroutine.yield(i)
end
end)
end
local co = range(3)
print(coroutine.resume(co))
Common mistakes
| Mistake | Fix |
|---|---|
| Using global variables where locals would do | Declare variables with local to avoid accidental sharing and name collisions. |
| Concatenating a nil value with a string | Check for nil or provide a default with the or operator before concatenating. |
| Forgetting that table indices start at one | Remember ipairs begins at index one, so adjust loops written from other languages. |
| Capturing the loop variable in every closure | Create a fresh local inside the loop so each closure keeps its own copy. |
| Returning multiple values into a single variable by accident | Use one variable per returned value to keep all the results. |
Practice
- Write a function sum(...) that adds any number of arguments and returns the total.
- Write a function minmax(...) that returns the smallest and largest of its arguments.
- Create a closure factory that produces functions multiplying their input by a fixed factor.
- Define a table with a colon method that increments an internal counter.
- Write a coroutine that yields the squares of the numbers from one up to a given limit.