corund
corund

Reputation: 177

Functions in Lua could store local values between calls?

I'm reading "Programming in Lua" and I don't understand behavior of function in Lua in this piece of code:

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

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

From my point of view each call c1() should return 1 because i is initialized to zero at the beginning of the of newCounter(). But it looks like line

local i = 0

is skipped in calls of c1(). And newCounter() behaves like object not like function. I know Scheme and C# a little, so I am familiar with first-class functions. Function return function it's ok for me, but how does it stores value of i between calls?

Upvotes: 4

Views: 306

Answers (2)

zzn
zzn

Reputation: 2455

you can treat i as a global variable only visible by C1.

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122383

This is the difference between a "normal" function and a closure.

To the anonymous function, i is NOT a local variable, it's not global either. It's called a non-local variable. Note that i is out of scope when you execute the anonymous function:

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

The point here is, the value of i is stored in the anonymous function. The function, and all the non-local variables, together make a closure.

Upvotes: 6

Related Questions