lua-users home
lua-l archive

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


On Mon, Nov 23, 2015 at 12:09 PM, Javier Guerra Giraldez
<javier@guerrag.com> wrote:
> but the real feature is clean up at block exit.  personally, I find
> Python-like "with" block nicer than "finally" clauses.

Depends on what you're doing with it. "with" blocks are nicer for
objects that know how to clean themselves up. "finally" clauses are
nicer if you need to write ad-hoc code in the cleanup block. Obviously
it's always possible to write either in terms of the other (and I
demonstrated this already) but if I had to choose one of the two... I
slightly favor finally's power-user leanings. (That said, I'd probably
use "with" if I were writing something for end-user scripting that
needed reliable cleanup, because for the simple cases it's harder to
screw up.)

>> with(io.open("filename.txt", "r"), function(f)
>>   -- do stuff with f
>> end)
>
> note that this handler assumes that the only cleanup needed is to call
> :close() on relevant values.  If the user needs something more
> generic, the syntax uglifyies significantly.

Which is why I provided finally(). It's not as visually attractive as
a native finally syntax, but it's not too bad. You can declare your
locals in advance of the call to finally() and populate them inside
the body, then those locals are still in scope in the finally block.

If you REALLY had to, you could always write { close = function() ...
end }. That's not HORRENDOUSLY ugly.

/s/ Adam