Relationship between global variables and environments

Free Names

  • Free names (Free Variables) are identifiers that are not within the context of
    • A local variable name
    • A for loop control variable
    • A function parameter
  • In other words they are what we have been calling Global Variables

_ENV and _G

  • _ENV is a local variable associated with a chunk (a lua file)
  • _ENV is initialize with a reference to the global table _G as the chunk is loaded
  • Each free variable in a chuck is referenced as _ENV.variableName
    • Since _ENV is a reference to _G any free variable goes into _ENV and _G
  • Therefore you can use _ENV within a file to limit the functions and globals that are seen
  • Function names are just global identifiers for function references

View of _ENV after it has been limited

_ENV variable in a debugger

  • Note that if _ENV is set to nil then references to existing free variables are lost