Free preview.You're sampling one lesson — enroll free to unlock all 10 lessons and track your progress.
Enroll free lesson
Closures and Higher-Order Functions
Closures and Higher-Order Functions
In this lesson — part of Advanced Features — you'll learn closures and higher-order functions in Lua and why it matters in real work.
Why it matters
Functions that take or return functions unlock concise, composable code.
Key ideas
- Functions as values
- map / filter / reduce
- Callbacks
- Composition
In practice
Here's how it looks in idiomatic Lua:
local function compose(f, g)
return function(...) return f(g(...)) end -- returns a new function
end
local inc = function(x) return x + 1 end
local double = function(x) return x * 2 end
local inc_then_double = compose(double, inc)
print(inc_then_double(5)) --> 12
table.sort(nums or {3,1,2}, function(a, b) return a > b end) -- fn argument
Lua note: Functions are ordinary first-class values, so passing them as arguments (like the comparator to table.sort) and returning freshly-built closures are both completely idiomatic.
Try it yourself
Exercise: In Lua, use map and filter to get the squares of the even numbers.
Recap
You now understand closures and higher-order functions and can apply it in Lua. Mark this lesson complete and continue to the next one.
