|
On 14 Mar 2016 04:25, "Dirk Laurie" <dirk.laurie@gmail.com> wrote:
>
> Thanks to everyone who replied. The present protocol is:
>
> --- with(tbl[,context])
> -- Creates a new table with write access to `tbl` and read access to
> -- `tbl` and `context`, which defaults to `_ENV`. If current _ENV
> -- is local or an upvalue, it must be explicitly given as `context`.
> -- If really no context is required, specify an explicit `nil`.
> -- Designed for the idiom
> -- do local _ENV=with(tbl)
> -- ...
> -- end
> -- which mimics the `with` keyword in Pascal, Visual Basic etc.
>
> The code is:
>
> local
> function with(tbl,...)
> local context = ...
> if select('#',...)==0 then context = _ENV end
> if context then
> return setmetatable({},{__newindex=tbl,
> __index=function(_,key) return tbl[key] or context[key] end})
> else
> return tbl
> end
> end
The optional context can't default to _ENV, as environments are lexical, and will be taken from the _ENV of where `with` is declared.