Factory Functions and Generators
Use closures as factory functions to produce configured function instances.
Factory Functions and Generators is a free Lua Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a Factory Function?
A factory function is a function that creates and returns other functions, configured by its arguments and upvalues.
Simple Multiplier Factory
Each call to multiplier returns a new closure capturing a different factor.
local function multiplier(factor)
return function(x) return x * factor end
end
local double = multiplier(2)
local triple = multiplier(3)
print(double(5)) -- 10
print(triple(5)) -- 15Configurable Logger Factory
A logger factory captures a prefix string and returns a log function.
local function makeLogger(prefix)
return function(msg)
print("[" .. prefix .. "] " .. msg)
end
end
local info = makeLogger("INFO")
local warn = makeLogger("WARN")
info("started")
warn("low memory")Counter Generator
A generator maintains internal state and produces a new value on each call.
local function counter(start, step)
local n = start - step
return function()
n = n + step
return n
end
end
local evens = counter(0, 2)
print(evens(), evens(), evens()) -- 0 2 4Range Generator
A range generator yields values from from to to, returning nil when exhausted.
local function range(from, to, step)
step = step or 1
local i = from - step
return function()
i = i + step
if i <= to then return i end
end
end
for v in range(1, 5) do print(v) endPartial Application
A factory partially applies arguments to create a specialized version of a function.
local function partial(fn, ...)
local args = {...}
return function(...)
local all = {table.unpack(args)}
for _, v in ipairs({...}) do all[#all+1] = v end
return fn(table.unpack(all))
end
end
local add = function(a,b) return a+b end
local add10 = partial(add, 10)
print(add10(5)) -- 15Memoizing Factory
A factory can build a memoized version of an expensive function.
local function memoize(fn)
local cache = {}
return function(x)
if cache[x] == nil then cache[x] = fn(x) end
return cache[x]
end
endStateful Token Lexer
A lexer factory captures the input string and position, yielding the next token on each call.
local function lexer(input)
local pos = 1
return function()
if pos > #input then return nil end
local token = input:match("%S+", pos)
if token then pos = pos + #token + 1 end
return token
end
endGenerators vs. Coroutines
Closure-based generators are simpler but carry all state in upvalues. Coroutine-based generators are more powerful, allowing yield anywhere in complex logic.
Function Templates
Factories create function templates — common patterns parameterized at creation time, reused many times with different configurations.
Currying
A curried function takes arguments one at a time, returning a new function until all arguments are supplied.
local function curry2(fn)
return function(a)
return function(b)
return fn(a, b)
end
end
end
local curriedAdd = curry2(function(a,b) return a+b end)
print(curriedAdd(3)(4)) -- 7Factory Question
What is a key characteristic of factory functions?
Recap: Factory Functions
Factory functions produce configured closures, enabling partial application, generators, memoization, and currying. They are one of Lua's most powerful functional patterns.
Frequently asked questions
Is the “Factory Functions and Generators” lesson free?
Yes — the full text of “Factory Functions and Generators” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.
What will I learn in “Factory Functions and Generators”?
Use closures as factory functions to produce configured function instances. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Lua Academy?
No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Factory Functions and Generators” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Lua Academy lesson?
Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- What Are Upvalues?
- Shared Upvalues Between Closures
- Factory Functions and Generators
- Memoization with Closures