Lesson 9 of 15
Closures
Closures
A closure is a function that captures variables from its enclosing scope. In Lua, functions are first-class values and naturally form closures:
function makeCounter()
local count = 0
return function()
count = count + 1
return count
end
end
local counter = makeCounter()
print(counter()) -- 1
print(counter()) -- 2
print(counter()) -- 3
Each call to makeCounter() creates a new, independent counter.
Anonymous Functions
Functions can be stored in variables:
local double = function(x)
return x * 2
end
print(double(5)) -- 10
Your Task
Write a function makeAdder that takes a number n and returns a function that adds n to its argument.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.