lua-users home
lua-l archive

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


On Fri, 16 Jul 2010 12:38:32 -0400, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:

Repeating again: the point is not to disallow global access, but to
prevent unintended creation of globals. Changing the environment
prevents the unintended creation of globals, but at a high cost (no
more access to globals including the standard libraries):

do
  local _ENV = nil
  a = 12345    --would result in "error: no environment"; fine
  local a = 12 -- fine, 'a' now is local
  print(a)     -- oops; error...
end

-- Roberto



What about this?

do
  local G = _ENV -- save the environment in a local G

local _ENV = nil -- remove the reference to the global table as environment

  G.a = 12345 -- "global variables" would just be explicit indexes -
-- the downside would be that any use of the global "a" would need -- a couple characters before every use, but if the developer chose to -- remove the environment, it's safe to say they're OK with that,
              -- and if they have to use globals a lot again in one section
-- of the code they can just enclose it within a "do local _ENV = G ... end"

local a = 12 -- all plain references to "a" unambiguously point to this local

-- Now, two ways to access print and all other globals including the standard libraries:
  G.print(a) -- explicitly index it out of the global table

  -- or --

  local print = G.print -- or local print = print if you do it before
                         -- removing the environment
  print(a)

end

Module authors have been using these two approaches (explicit indexing and localization) for years without complaint.