Page 2 of 2

Re: Why use local variables?

Posted: Fri Aug 30, 2013 8:39 am
by vrld
Not sure why no-one mentioned this yet, but local variables are the only way to create closures. A toy example:

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
Or this

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

Re: Why use local variables?

Posted: Sat Nov 02, 2013 8:58 am
by seeker14491
vrld wrote:

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
b is nil, so that last line would error.

Re: Why use local variables?

Posted: Sat Nov 02, 2013 10:41 am
by Roland_Yonaba
seeker14491 wrote:b is nil, so that last line would error.
True. I guess what vrld wanted to mean was:

Code: Select all

    -- same as before ...
    a, b = newCounter(), newCounter()
    -- same as before ...