lua-users home
lua-l archive

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


So it turns out that wrapping with another function gets me what I want.

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

My previous example fails regardless of whether it's called recursively, since, as you pointed out, I was only creating one environment table.

All I'm really trying to do is get rid of the excessive use of the local keyword inside large "object generating" functions, where it's easy to miss one and cause a hard to find bug.


On 11/5/07, Gé Weijers <ge@weijers.org> wrote:
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