lua-users home
lua-l archive

Re: setfenv (was Re: tuples)

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


Mark Hamburg said:
> on 9/15/05 10:42 AM, Rici Lake at lua@ricilake.net wrote:
>
>> Lua functions are
>> actually mutable objects -- you can call setfenv on them
>
> Which is an annoyance in a variety of ways.
>
> 1. It cries out for a way to duplicate a function so that you can set the
> environment for the duplicate without changing the original.
Agreed.
> An alternative to setfenv which would be less powerful but would avoid
> these
> issues would be to provide the environment as an argument to the chunk
> compiler.
That's certainly worth thinking about. Another possibility, which Wim and
I discussed at some length a couple of years ago (and which recently
resurfaced, I believe) is the "in <expr> do ... end" statement, which
makes <expr> the table for unbound variable lookup within the syntactic
scope of the do...end clause.
This allows you to create a wrapper which is quite flexible:
function(env)
 in env do
 return function()
 -- insert code here
 end
 end
end
Now every time this factory is executed, it creates a new instance of the
embedded code with a different environment.
You could also create objects with mutable environments:
function(env)
 in env do
 return {
 setenv = function(e) env = e end,
 call = function()
 -- insert code here
 }
 end
end
This seems to capture a wide variety of use cases while still permitting
that:
> ... it might be nice to fully embrace the mutability of
 ^^ immutability, no?
> functions and provide a way to duplicate them.
>
> Mark
>

AltStyle によって変換されたページ (->オリジナル) /