lua-users home
lua-l archive

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


Thank you, Peter. It cleared a lot.

----- Original Message ----- 
From: "Peter Shook" <pshook@hotmail.com>
To: <lua@bazar2.conectiva.com.br>
Sent: Thursday, June 05, 2003 1:13 AM
Subject: Re: one more little thing about upvalues


> 
> 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:  http://lua-users.org/wiki/MinimisingClosures
> 
> Any good book on Perl should will talk about closures.
> http://www.perl.com/pub/a/2002/05/29/closure.html
> 
> 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.
> 
> do
>   local name = 'bob'
> 
>   function print_name()
>     print('name', name)
>   end
> end
> 
> -- cannot access name directly from here on, but print_name can
> 
> print_name()
> 
> -- Here is a simple example:
> 
> function make_counter(count)
>   local function counter()
>     local c = count
>     count = count + 1
>     return c
>   end
>   return counter
> end
> 
> 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.  
> http://join.msn.com/?page=features/junkmail
> 
> 
>