lua-users home
lua-l archive

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

On Mon, Nov 23, 2015 at 2:38 PM, Coda Highland <> wrote:
> Deterministic finalization is a means to a particular end, but what is
> that desired end? Ultimately: We want a specific function to be called
> when control exits a block, no matter how it exits. In C++, we do this
> using block scoping on a local variable. In Python, we have "finally:"
> blocks and we have context managers and the "with" keyword; Java has
> finally and try-with-parameters for the same.

totally concur with you on this.  far too many people say (not only
about Lua) something on the lines of "professional programmers do
RAII, therefore static languages are the only professional tools".
(spotting other non-sequitur are left as an exercise)

but the real feature is clean up at block exit.  personally, I find
Python-like "with" block nicer than "finally" clauses.

> You could even create a context handler:
> function with(...)
>   var args = table.pack(...)
>   var method = args[args.n]
>   finally(method(table.unpack(args, 1, args.n-1)),
>     function()
>       for i in 1, args.n-1 do
>         args[i]:close()
>       end
>     end
>   )
> end
> with("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.