[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: 'with' statement
- From: Dirk Laurie <dirk.laurie@...>
- Date: Mon, 14 Mar 2016 07:16:53 +0200
2016-03-14 4:31 GMT+02:00 Daurnimator <quae@daurnimator.com>:
>
> 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.
In an earlier version of the comments, the phrase "which defaults to `_ENV`"
said "which defaults to `_ENV` at the time when `with` is loaded" and the
first paragraph ended there. I thought the issue needed a bit of spelling out
and replaced it by the sentence starting `If current _ENV ...".
It seems that both are needed :-)
Thanks.