lua-users home
lua-l archive

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


my 2¢:

On 24 June 2016 at 18:48, Viacheslav Usov <via.usov@gmail.com> wrote:
> The different angle was the desire to have local objects finalized upon
> leaving their syntactical scope because some of those objects could hold
> some expensive resources, such as DB connections.

RAII is a nice idea for static, OO-heavy projects, but it's at odds
with more dynamic styles.  I like the description in the Scheme
papers:

"All objects created in the course of a Scheme computation, including
procedures and continuations, have unlimited extent. No Scheme object
is ever destroyed. The reason that implementations of Scheme do not
(usually!) run out of storage is that they are permitted to reclaim
the storage occupied by an object if they can prove that the object
cannot possibly matter to any future computation."

IOW: GC is not about making it simpler to dispose of objects.  it's
about never destroying them... unless you won't notice it.  therefore,
adding semantics to it goes against the essence of invisibility.

Of course, seeing that _so many_ people want RAII, it seems that
there's a message there.  The Python answer is context managers.  A
very common (and useful!) case it about opening files:

    with open('some/file.txt) as f:
        ...do things with f ...
    #file is closed here

in Lua it could be something like

    function with(o, f, m)
        local ok = pcall(f, o)   -- add lots of error handling
        o[m](o)
    end

    with(open('some/file.txt'), function(f)
        ...do things with f...
    end, 'close')


(i'm quite rusty with pcall(), but i think the intention is clear...)
of course, it would be a _lot_ better to avoid the function creation,
and instead have some language support to hook resource release
directly to scope exit:

    do
        local f = open(...)
        onexit do f:close() end
        .... do things with f ....
    end


and having the block in the onexit do .... end execute on any exit
from the surrounding block.  of course, it should be possible to add
several onexit do...end clauses.  a bit like go's 'defer' keyword
(which is an example of non-RAII for a garbage-collected language,
albeit an static one)


-- 
Javier