lua-users home
lua-l archive

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

On Sat, Jan 9, 2010 at 3:26 PM, Leo Razoumov <> wrote:
> in {x = 1, y = 10, print=print} do print(fn()) end  -- 11

Afraid not!

> in {x=1,y=10,print=print,fn=fn} do print(fn()) end
[string "return x + y"]:1: attempt to perform arithmetic on global 'x'
(a nil value)

To quote the manual:

A lexical environment defines a new current environment (see §2.9) for
the code inside its block:

	stat ::= in exp do block end

That is, a lexical environment changes the table used to resolve all
accesses to global (free) variables inside a block.

Inside a lexical environment, the result of exp becomes the current
environment. Expression exp is evaluated only once in the beginning of
the statement and it is stored in a hidden local variable named
(environment). Then, any global variable (that is, a variable not
declared as a local) var inside block is accessed as
(environment).var. Moreover, functions defined inside the block also
use the current environment as their environments (see §2.9).

A lexical environment does not shadow local declarations. That is, any
local variable that is visible just before a lexical environment is
still visible inside the environment.