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()
if x > i then return null end
return x
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.
for i in counter(5) do
for j in counter(5) do
sum = sum + j
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

t.withdraw = function(amount)
balance = balance - amount
return balance


t.getBalance = function()
return balance


return t

account = newAccount(1000)

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.