lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It's not quite clear to me what you are trying to achieve. The 'environment' you can set refers to global variables only. So all recursive instances of your function (closure) will use the same environment table, and share the same set of global variables, which is what languages that use lexical scope usually do. Your code only creates one environment. Local variables defined inside the function will not be shared.

What did you expect to happen?

On Nov 4, 2007, at 9:33 PM, Matthew Armstrong wrote:

Is it possible to use setfenv recursively?  When I call setfenv, it attaches to the function, but it seems like it should more naturally attach to the function's call. 

I have a little wrapper function to protect my environment:

function protectedEnv(func)
    local env = {}
    setmetatable(env, { __index = _G })
    setfenv(func, env)
    return func
end

...

myFunc = protectedEnv(
    function()
        -- If I call myFunc inside here, my environments start colliding.
    end)
   
...

myFunc()





--
Gé Weijers