< HelloWorld | CodeSamples | FunctionVariableArguments >
---% Code tested with Luxinia 0.96alpha build Dec 21 2006
---% at 12/29/06 11:30:40
-- Function environment sample
str = [[
for i=1,arg.n or #arg do
print(arg[i])
end
]]
fn = assert(loadstring(str))
env = {}
setmetatable(env,
{
__index = _G, -- delegate all
-- reading access on global
-- variables to our global
-- environment
__newindex = _G, -- delegate all
-- writing access on global
-- variables to our global
-- environment
})
setfenv(fn,env)
-- set the environment to our function
-- we can read and write now global
-- variables from our function,
-- however, we can manipulate some
-- variables by manipulating its
-- environment
env.arg = {1,2,3} -- let arg be 1,2,3
fn() -- will print 1 2 3
env.arg = {"hello","World"}
fn() -- will print hello World
rawset(env,"print",function () end)
-- let's disable printing in our function
-- we need to use rawset, otherwise the __newindex
-- operator of the env table would overwrite
-- our printing function in the global environment
fn() -- won't print anything
print "finished"
