lua-users home
lua-l archive

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

jason zhang wrote:
I am one of those who don't know upvalues and closure:-)
However, I'd like to find a tutorial about that. The manual
seems to be not clear on that. Thanks for any help.

Rici uses closures a lot so look for his stuff in the list archive.

there is stuff on the wiki:

Any good book on Perl should will talk about closures.

And here is a simple example.

$ cat closure.lua

-- To quote Damian Conway:
--   A closure is just a function that refers to one or more lexical
--   variables declared outside the function itself.

 local name = 'bob'

 function print_name()
   print('name', name)

-- cannot access name directly from here on, but print_name can


-- Here is a simple example:

function make_counter(count)
 local function counter()
   local c = count
   count = count + 1
   return c
 return counter

counter1 = make_counter(10)
counter2 = make_counter(100)

print( 'c1', counter1(), 'c2', counter2() )
print( 'c2', counter2() )
print( 'c2', counter2() )
print( 'c1', counter1() )
print( 'c1', counter1(), 'c2', counter2() )

$ lua closure.lua
name    bob
c1      10      c2      100
c2      101
c2      102
c1      11
c1      12      c2      103

- Peter Shook

Tired of spam? Get advanced junk mail protection with MSN 8.