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. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.
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.
Learn Lua with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 40
- Lessons
- 159
Frequently Asked Questions
Is the “Factory Functions and Generators” lesson free?
Yes — any 3 lessons of the Lua Academy learning path, including “Factory Functions and Generators”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
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