FactoryFunctions

Factory Functions

A factory function is a design pattern used in programming where a function is responsible for creating and returning another function or object. It acts as a "factory" that produces instances of a certain type, often with customizable behavior or configuration.

See example: Lua.org subchapter 16.4


Counter

The function, that returns the function with counter:

function createCounter(startValue)
	local count = startValue or 0  -- Initial count

	-- the returned function is the actual counter function
	local function counter()
		-- adding 1 to the counter
		count = count + 1
		
		-- return count value
		return count
	end

	-- return generated function
	return counter
end

Usage:

-- create first counter:
local counter1 = createCounter()

print(counter1())  -- 1
print(counter2())  -- 2

-- create second counter with initial value:
local counter2 = createCounter(12)

-- keep counting:
print(counter1())  -- 3
print(counter2())  -- 13

-- keep counting:
print(counter1())  -- 4
print(counter2())  -- 14