lua-users home
lua-l archive

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


Quoth meino.cramer@gmx.de, on 2012-07-07 21:27:37 +0200:
> 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
[...]

You can wrap the first part in a do..end block so that the scope of N
ends after the increment function is defined:

do
  local N = 0
  function increment()
    N = N + 1
    return N
  end
end

However, note that then illegal_decrement will access the global N
(and fail if it's not a number), since global accesses are not checked
at load time in plain Lua.  Additionally, local definitions are not
visible past the end of a chunk, so if you're only worried about
functions in other chunks then you're fine either way.

   ---> Drake Wilson