0Pricing
Lua Academy · Lesson

Composing Functions

Chain transformations.

What Is Composition?

Function composition combines two functions into one. The composed function feeds its input through the first function, then passes that result to the second.

In math this is written f(g(x)). Composition lets you build big transformations out of small, focused functions.

Composing Two Functions

A compose helper takes two functions and returns a new one. Calling it runs g first, then feeds the result into f.

The order matters: the inner function runs first, the outer function runs on its output.

local function compose(f, g)
  return function(x)
    return f(g(x))
  end
end

local function inc(n) return n + 1 end
local function dbl(n) return n * 2 end

local incThenDouble = compose(dbl, inc)
print(incThenDouble(3))

All lessons in this course

  1. Functions as Values
  2. map, filter, reduce
  3. Partial Application
  4. Composing Functions
← Back to Lua Academy