lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


When you call newCounter(), you’ll create a new instance of j (the definition is within newCounter), but reuse the existing i (its definition is outside newCounter).

 

So both (or all if you create more) counters share i, which indeed increments from 1 to 5, the second number printed increments only for the separate calls to either c1 or c2.

 

HTH

Thijs

 

From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org] On Behalf Of Minh Ngo
Sent: vrijdag 16 maart 2012 6:30
To: lua-l@lists.lua.org
Subject: Lua closure and non-local variables

 

Hello, there is an example in Programming in Lua chapter 6.1 about closures. I made a small change in the example to see if the results are the same, but they are not;
I changed the counter to keep count of an extra local variable outside of newCounter function. My understanding of closure is that they are another word for functions remembers the instances of its external local variables.
Why don't c1 and c2 have different instances of of i? Please bear with me as I'm very new at programming.

do
    local i = 0
   
    function newCounter ()
        local j = 0
        return function ()    
            i = i + 1
            j = j + 1
            return i, j
        end
    end
end

do
    local c1 = newCounter()
                   --> i  j
    print(c1()) --> 1  1
    local c2 = newCounter()    
    print(c1()) --> 2  2
    print(c2()) --> 3  1
    print(c1()) --> 4  3
    print(c2()) --> 5  2
end