title: Recreating setfenv() in Lua 5.2
body: <p>How can I recreate the functionality of <code>setfenv</code> in Lua 5.2? I'm having some trouble understanding exactly how you are supposed to use the new <code>_ENV</code> environment variable.<br><br></p>
  
  <p>In Lua 5.1 you can use <code>setfenv</code> to sandbox any function quite easily.</p>
  
  <pre><code>--# Lua 5.1
  
  print('_G', _G)             -- address of _G
  
  local foo = function()  
      print('env', _G)        -- address of sandbox _G
      bar = 1
  end
  
  -- create a simple sandbox
  local env = { print = print }
  env._G = env
  
  -- set the environment and call the function
  setfenv(foo, env)
  foo()
  
  -- we should have global in our environment table but not in _G
  print(bar, env.bar)
  </code></pre>
  
  <p>Running this example shows an output:</p>
  
  <pre><code>_G    table: 0x62d6b0
  env   table: 0x635d00
  nil   1
  </code></pre>
  
  <p><br><br>
  I would like to recreate this simple example in Lua 5.2. Below is my attempt, but it does not work like the above example.</p>
  
  <pre><code>--# Lua 5.2
  
  local function setfenv(f, env)
      local _ENV = env or {}       -- create the _ENV upvalue
      return function(...)
          print('upvalue', _ENV)   -- address of _ENV upvalue
          return f(...)
      end
  end
  
  local foo = function()
      print('_ENV', _ENV)          -- address of function _ENV
      bar = 1
  end
  
  -- create a simple sandbox
  local env = { print = print }
  env._G = env
  
  -- set the environment and call the function
  foo_env = setfenv(foo, env)
  foo_env()
  
  -- we should have global in our envoirnment table but not in _G
  print(bar, env.bar)
  </code></pre>
  
  <p>Running this example shows the output:</p>
  
  <pre><code>upvalue    table: 0x637e90
  _ENV       table: 0x6305f0
  1          nil
  </code></pre>
  
  <p><br><br>
  I am aware of several other questions on this subject, but they mostly seem to be dealing with loading dynamic code (files or string) which work quite well using the new <code>load</code> function provided in Lua 5.2. Here I am specifically asking for a solution to run arbitrary functions in a sandbox. I would like to do this without using the <code>debug</code> library. According to the Lua <a href="http://www.lua.org/manual/5.1/manual.html#5.9" rel="noreferrer">documentation</a> we should not have to rely on it.</p>