0Pricing
Lua Academy · Lesson

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))  -- 15

All lessons in this course

  1. What Are Upvalues?
  2. Shared Upvalues Between Closures
  3. Factory Functions and Generators
  4. Memoization with Closures
← Back to Lua Academy