lua-users home
lua-l archive

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


>From lua-l@tecgraf.puc-rio.br Wed Jul 28 23:16:17 1999
>From: Dave Bollinger <DBollinger@compuserve.com>

>I wonder why can't a local function access an
>enclosing function's local variables?
>I understand the explanation that the
>variable might no longer exist - and I *assume* that this is because Lua
>needs to be able to make a compile-time decision on this issue, yes? 

No. The whole point is that the "enclosing" scope might no longer exist
when the function is executed. Remember that functions are first-class values
and may be returned from functions:

 function f()
	 local a=1
	 return function (x) print(x+a) end	-- ERROR: cannot access 'a'
 end

 g=f()
 g(2)

If you expect g(2) to print 3, then that's exactly what upvalues are for:
you should write

 function f()
	 local a=1
	 return function (x) print(x+%a) end	-- ok now
 end

Otherwise, what would x+a mean inside g?
The whole point of the '%' notation is to signal that the *value* of 'a'
is being used, not the variable itself.

> How is it different from this (which does work):

 fl = nil
 function g(a)
   local gl = fl -- no problem referencing a global, even if nil
   print(gl) -- gl is of course itself still nil
 end
 g(123)

This does work because g gets the value of the global fl when it runs.
If you do fl=12 after defining g but before calling it, 'g' will use 12,
not nil. To use nil, you should 'freeze' the value of 'fl', by using an upvalue.
So, upvalues have less to do with scope and visibility than with freezing
values.

Upvalues take some getting used to, but they are powerful.
--lhf