lua-users home
lua-l archive

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


>> 1)  Globals live in a table called _G, any function has a variable called _ENV which is the same table unless I explicitly redefine it in which case for that function's life globals are whatever is in the table pointed to by _ENV.  (_G and DEFAULT_ENVIRONMENT you  mentioned are the same thing?)
>
> I'm personally not a fan of referring to _G as a specific object, but yes.
>

Not quite.

1. Globals live in whatever table is currently associated with the name
_ENV.
2. Whenever you enter a function, Lua has pre-initialized _ENV
for you, so that _ENV and _ENV._ENV are the same.
3. _G is a key in the original _ENV.  The only special thing
about _G is that Lua initializes _ENV._G to _ENV right at the
start.
4.  Lua never again changes or refers to _G.  It's there for
your convenience only.
5. If you never muck about with _ENV or _G, Lua automatically
provides an _ENV in which _ENV._G (i.e. _G) still refers to the
original global environment

Let's execute some code in which _ENV is modified.

Lua 5.2.0 (alpha)  Copyright (C) 1994-2010 Lua.org, PUC-Rio
> print(_ENV,_G); _ENV=nil; print(_ENV,_G)
table: 0x9fb13b0	    table: 0x9fb13b0
stdin:1: attempt to index upvalue '_ENV' (a nil value)

After `_ENV=nil`, there is no _G anymore until _ENV is redefined,
for example by returning from the current function.

> _G=nil; f=function(_ENV) print(_G) end;
> f(_ENV)
nil
> f{print=print,_G="ha-ha!"}
ha-ha!

If you supply your own _ENV, you must do something like that
`print=print`, or providing a suitable __index metamethod, if
you will need access to routines in the standard library.