What are function environments?

setfenv can set the environment for a function. Normally, the environment for a function is the global table, but this can be changed. This is very useful for sand boxing, because you can control the context in which code is executed, and prevent that code from doing anything nasty. It is also used to implement module scope.

function test ()
 return A + 2*B end t = { A = 10; B = 20 }
setfenv(test,t)
print(test())
=>
50

Function environments have been removed from Lua 5.2, but there are equivalent mechanisms of equal power available. Say you wish to compile some code in a particular starting environment; the extended load function can be passed code, a name for the code, the mode ("t" here for text only) and an optional environment table. load compiles the code, returning a chunk function that then needs to be evaluated:

Lua 5.2.0 (beta) Copyright (C) 1994-2011 Lua.org, PUC-Rio
> chunk = load("return x+y","tmp","t",{x=1,y=2})
> = chunk function: 003D93D0
> = chunk()
3

You can use this to load user scripts in a controlled environment; in this case the 'global' table just contains the specified two variables.

The Lua 5.1 setfenv example can be written using the special _ENV variable in Lua 5.2:

> function test(_ENV) return A + 2*B end
> t = {A=10; B=20}
> = test(t)
50



Back