lua-users home
lua-l archive

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




On 2019-06-20 6:13 p.m., Patrick Donnelly wrote:
On Thu, Jun 20, 2019 at 2:07 PM Dibyendu Majumdar
<mobile@majumdar.org.uk> wrote:
>
> On Thu, 20 Jun 2019 at 21:59, Patrick Donnelly <batrick@batbytes.com> wrote:
> >
> => > 2) With regards to the 'toclose' variable declaration, introducing a
> > > 'with' statement is the nicest approach.
> > >
> > > with <vars> = <initializers> do
> > >
> > > end
> > >
> > > This idiom is familiar to most programmers who use Python.
> > > BTW @Patrick Donnelly this has nothing to do with Python's reasons for it etc.
> >
> > Quoting myself from the prior thread:
> >
> > "I want to point out the reasons why Python requires a control
> > structure but Lua would not: Python's locals are function-scoped.
> > Declaring a local in Python means it doesn't go out of scope until the
> > function returns. For this reason, Python requires an explicit control
> > structure to define the lifetime of the variable. Lua does not have
> > this limitation."
> >
> > They absolutely needed another control structure to implement their
> > flavor of RAII.
> >
>
> And I repeat that the suggestion to use this syntax doesn't have
> anything to do with why Python had to have it. It is a nice idiom used
> in many languages. C# calls it 'using'. In Java we have try with
> resources. But all are the same construct.

Fine, but I haven't seen a good argument for __enter so a "with"
construct looks unnecessary, distracting, and unnecessary indentation.


a "with" construct is unnecessary even with __enter, and I'd argue it'd be beneficial to have __enter without "with": assignment to a toclose variable (or uh, a with variable) would cause __enter, and when it goes out of scope, an __close.

e.g. let's say you want a function that can be passed a file directly or as part of a larger processing chain:

local function do_something_with_file(f)
    local <with> f = f -- f:__enter()
    f:write("hello!\n")
    -- f:__close()
end

do_something_with_file(io.open("foo", "w")) -- okay, file gets closed

local <with> f = io.open("bar", "w") -- f:__enter()
do_something_with_file(f) -- doesn't close file
f:write("goodbye!\n")
-- f:__close() -- file gets closed