lua-users home
lua-l archive

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

2012/6/5 Rena <>:
> I think people tend to forget about a powerful capability of Lua that
> requires implicit globals: you can use metatable/_ENV magic to make
> your "globals" not really global.
> ...
> Really, does Lua 5.2 even have "global" variables anymore? Unless I'm
> misunderstanding, anything not declared "local" is looked up in _ENV,
> which can be redefined at will, and may or may not be accessible from
> higher scopes.

Very true.  We're not quite used to 5.2 yet.  New idioms have to be acquired.

-- fake syntax for global access
function foo()
local global=_ENV
local a,b,c = a,b,c  -- cache values of some global values
local _ENV=nil    -- no globals known anymore
global.   d=b^2-4*a*c   -- export new value

-- Someone else has already pointed out the versatile trick below
-- but I can't find it now.  NB: no genuine globals visible here.
function kwd_arg(_ENV)
d = b^2-4*a*c -- This `d` is NOT implicitly global!
return d

> a=1; b=2; c=3
> foo()
> print (kwd_arg{a=4,b=6,c=9}) --> -108
> print(d) --> -8