lua-users home
lua-l archive

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


try-catch and try-finally language sugars for pcall to simplify error handling

Em Sáb, 15 de set de 2018 07:54, John Hind <john.hind@zen.co.uk> escreveu:
At risk of the ire of the old-timers, I'll try bouncing my enhanced
generic 'for' powerpatch again. The Lua Users WiKi now has a full
implementation with both code and documentation patches and I have been
using it myself for years now.

In summary, at present a function is expected after 'for', followed by
two optional state variables, conventionally supplied by a call to
'pairs' (or to the 'ipairs' bloat alternative), but you can also write
your own either on the 'pairs' pattern or as a direct iterator function
which stores its state in upvalues. My patch provides fallback behaviour
if presented with a non-function and no further variables. First it
looks for a metamethod '_iter' and failing that it uses an internal
implementation of 'pairs'. This enables iteration of objects directly.
The 'iter' metamethod allows supply of a default iteration method for
tables and userdata used to implement the OO paradigm while the 'pairs'
substitute enables quick and easy iteration of anything that can be
iterated which always works regardless of any messing about with the
globals (particularly useful in debugging).

With this change, we support a simpler alternative construct which is
more intuitive and familiar from other languages:

'for my_item in my_collection do print(my_item) end'

whilst preserving Lua's more sophisticated and extensible multi-iterator
capability. To those who object on 'bloat' grounds, combine with removal
of 'ipairs' and the 'pairs' and 'ipairs' metamethods and you actually
have a simplification both conceptually and in implementation.

In all the years I've been pushing this change, I've never seen a
convincing objection.