Factory Functions and Generators
Use closures as factory functions to produce configured function instances.
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)) -- 15All lessons in this course
- What Are Upvalues?
- Shared Upvalues Between Closures
- Factory Functions and Generators
- Memoization with Closures