lua-users home
lua-l archive

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

It's very nice to see these fruits from to-be-closed variables.
Belmonte's ideas were the main motivation for this feature in Lua.

-- Roberto

The motivating use case for to-be-closed was to have more ergonomic cleanup-- that is, something answering the demand for try/finally, without requiring a disruptive lambda for the `try` code.  It would be a nice little utility for someone to try implementing, and would be immediately useful to any Lua program.

The ubiquitous try/finally (and try/catch) language syntax is far from ideal, because you can end up with a lot of nesting, the finalization code can be far removed from where the resource were opened, and it doesn't support conditional finalization well.  So it's good that Lua never had this, and can leapfrog to something better.

Outline:  open a to-be-closed "scope manager" that handles cleanup within the local block of code.  Any number of cleanup functions can be registered with the manager, via methods like `on_exit()`, `on_failure()`, and `on_success()`.  The registered functions will be invoked in reverse order, as warranted, when the scope exits. 

See Python's `ExitStack` or D language's `scope guard` for inspiration.  This was also covered in my Lua Programming Gems chapter on exceptions, under "A simple scope manager"--  but I suspect few have the patience for a hard-copy book these days.