lua-users home
lua-l archive

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


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