Question about anonymous function using a simple example

CODE (Using a counter), taken from Pg 48 in Programming in Lua:

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

RESULT:

c1 = newCounter ()
print(c1()) -->1
print(c1()) -->2

QUESTION:

How did calling the print function a second time result in "2" instead of "1"? More specifically, at the second time, how did it bypass "local i = 0"?

Thanks in advance!

C1 is actually equal to a function (you see the "return")
C1 is initially set with i = 0 (the actual function has not yet executed)

upon calling this "returned" function, the function is executed producing 1

again and the function is executed producing two.

just notice what C1 really is, a function.

Thanks for your reply, TRTK!

After beating my head against my book for 30 min, I just had to post my question.

Now that you've explained it, I see how simple it now is. Sometimes an extra set of eyes is needed, you know, and I was just thinking too hard because I'm anxious to get through this book so I can build some games!! :-)

Take care!

Glad I could help. I know how it is. Good luck with your game coding!

views:1486 update:2011/10/5 8:48:05
corona forums © 2003-2011