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.
One of the simplest examples of using a closure is to create an iterator function which can be
used in
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
In the example above, each time the counter function is called, it creates a new iterator
function. The values of the local variables x and i are bound to that instance of the iterator
function and are not accessible from any other function. Function parameters are always considered
to be local variables as are any variables which are declared using the local keyword. The counter
function can be used in combination with a for loop as shown
below.
sum=0
for i in counter(5) do
for j in counter(5) do
sum = sum + j
end
end
The closure concept can also be used to support data privacy for object oriented programming as
is shown in this next
example.
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.