What are closures in Lua?
Archive - Originally posted on "The Horse's Mouth" - 2009-07-31 14:06:22 - Graham EllisWhen you're writing a sort routine, passing in "a" and "b" to be compared, how do you access other data that's needed in association with a and b? If - for example - a and b are keys to a hash or dictionary or associative array, and you want to sort based on the values in that array? You could make your hash global (or rely on the global default in Perl or Lua) but that is a poor solution - messy and unmaintainable.
Lua uses the concept of a closure - in Lua, variables that are local to a function are also available in functions that are defined within that function i.e. within nested definitions, or 'within the outer closure'.
Here's an example:
function postman(thistable)
function psord(a,b)
if thistable[a] < thistable[b] then
return true
end
return false
end
local keys = {}
for k,_ in pairs(thistable) do
keys[#keys+1] = k
end
table.sort(keys,psord)
rs = ""
for k,v in ipairs(keys) do
rs = rs .. k .. " " .. v .. " at no. ".. thistable[v].."\n"
end
return rs
end
deliveries = {John = 4, Jim = 10, Jean = 7, Joanna = 3, Jo = 9}
hegoes = postman(deliveries)
io.write (hegoes)
You'll notice that "thistable" is a local (parameter) to postman, but never the less can be accessed from within psord ... which is a pleasant surprise if you're converting from other languages.
Running the code, I get
1 Joanna at no. 3
2 John at no. 4
3 Jean at no. 7
4 Jo at no. 9
5 Jim at no. 10
Source of the example here