setfenv

Sets a function's environment

Prototype

f = setfenv (f, env)

Description

Sets the current environment to be used by f, which can be a function, userdata, thread or stack level. Level 1 is the current function. Level 0 is the global environment of the current thread. The "env" argument is a table, which effectively becomes the "root" for the environment.

The return value is the function whose environment was changed, unless the argument was 0.

function f (v)
  test = v  -- assign to global variable test
end -- function f

local myenv = {}  -- my local environment table
setfenv (f, myenv)  -- change environment for function f
f (42)  -- call f with new environment

print (test) --> nil  (global test was not changed)
print (myenv.test)  --> 42  (test inside myenv was changed)
This can be used as a form of "sandbox", so that functions can run in an environment where they do not have access to normal global variables. For example, in the above code, you could not call "print" from inside function f, as print is not in the environment. To make it accessible you might do this:

myenv.print = print -- copy print function into environment table
A nice use of the setfenv function is to limit the damage that can be done when reading an external file.
An example is to let the user of your script provide a configuration file, that you want to read in. An example might be:

a = 42
b = "nick"
c = { "the", "quick", "brown", "fox" }
A quick way of processing that file would be to: dofile ("config.txt")
However if the "config.txt" file contained malicious code (like: os.remove "myapplication.exe") then it could have undesired side-effects. Even a simple assignment like: 'print = nil' could cause problems. The solution is to use setfenv to limit the global environment for this file, like this:

config = {} -- empty environment table
-- load the file, get a function to execute  
local f = assert (loadfile ("config.txt"))
-- want to load file into the config table
setfenv (f, config)
-- load it
f ()
print (config.a)  --> 42 
What this does is change the global environment for the function returned from loadfile to be the empty config table. This means that all "global" variables will be relative to config, not _G. It also means that all the standard functions (like os.remove) are not visible.

Lua functions

Topics