[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: 'with' statement
- From: Dirk Laurie <dirk.laurie@...>
- Date: Sun, 13 Mar 2016 19:25:16 +0200
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
2016-03-10 10:09 GMT+02:00 Thijs Schreijer <thijs@thijsschreijer.nl>:
>
>> I never thought I'd say this, but I like the way Visual Basic 6 does it:
>> with foo
>> .x = 1
>> .y = some_local_var
>> end with
>> I don't remember the exact syntax, but the important part is you still
>> included the dot from foo.x, so that distinguished properties from other
>> variables in outer scopes.
>
> While reading up the thread, I had the same thought. I also like that about VB.
>
> Thijs