lua-users home
lua-l archive

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


TNHarris <telliamed@whoopdedo.org> [12-07-07 21:20]:
> On Saturday, July 07, 2012 03:12:35 PM meino.cramer@gmx.de wrote:
> > Hi,
> > 
> >  is there a concept of static local variable in function
> >  as it exist in C?
> > 
> 
> Lexical scoping and upvalues provide it.
> 
> in C:
> 
>     int increment(){
>         static int N = 0;
>         N = N + 1;
>         return N;
>     }
> 
> in Lua:
> 
>     local N = 0
>     function increment()
>         N = N + 1
>         return N
>     end
> 
> -- 
> tom <telliamed@whoopdedo.org>
> 


Hi Tom,

thanks for reply! :)

A small modification of your code:
     local N = 0
     function increment()
         N = N + 1
         return N
     end
 
     function illegal_decrement()
         N = N - 1
         return N
     end
 

In this case illegal_decrement should not have access to N since

     int increment(){
         static int N = 0;
         N = N + 1;
         return N;
     }
     int decrement(){
         N = N + 1;
         return N;
     }

the decrement() will fail with unresolved symbol or similiar...

How can I mimic this in Lua?

Best regards,
mcc