Re: Why use local variables?
Posted: Fri Aug 30, 2013 8:39 am
Not sure why no-one mentioned this yet, but local variables are the only way to create closures. A toy example:
Or this
Code: Select all
messages = {'hey!', 'listen!'}
closures = {}
for i = 1,10 do
local m = messages[math.random(#messages)]
closures[i] = function() print(m) end
end
for _, f in ipairs(closures) do
f()
end
Code: Select all
function newCounter()
local i = 0
return function(inc)
i = i + (inc or 1)
return i
end
end
a, b = newCounter()
print(a(3)) --> 3
print(a(), b()) --> 4, 1