Closures
Lua is a functional programming language with full support for closures. When a new function is created, any local variables become bound to that instance of the function. This can be used to create iterator functions as well as to create private variables for object oriented programming.
a
for
loop.function counter(i)
local x=0
return function()
x=x+1
if x > i then return null end
return x
end
end
sum=0
for i in counter(5) do
for j in counter(5) do
sum = sum + j
end
end
function newAccount(balance)
local t={}
t.deposit = function(amount)
balance = balance + amount
return balance
end
t.withdraw = function(amount)
balance = balance - amount
return balance
end
t.getBalance = function()
return balance
end
return t
end
account = newAccount(1000)
account.deposit(100)
account.withdraw(500)
balance = account.getBalance()
It is more common to use metatables to create objects than it is to use closures, but metatables do not provide a good way to implement data privacy as can be done using closures.