lua-users home
lua-l archive

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


Date: Sat, 24 Mar 2018 09:05:59 +0200
From: Dirk Laurie <dirk.laurie@gmail.com>

2018-03-24 8:11 GMT+02:00 Sergey Zakharchenko <doublef.mobile@gmail.com>:

IIUC, the OP's "conservative" proposal is merely that 'pairs' should
not discard extra arguments, i.e. it should trigger __pairs(tbl,...)
rather than just _pairs(tbl).

Note I never wrote about changing meaning of any existing Lua core
functions.

True, you do not suggest changing what 'pairs' does in the absence of
a metamethod. In fact, I wrote that interpretation  precisely to
emphasize that the proposal that 'pairs' should have a second argument
did not come from you.

Reread original email if that's not obvious.

Maybe you should take your own advice here. The original says clearly:
"If __pairs is invoked wth a second argument ..."

You can't change the way '__pairs' is called without changing 'pairs'
itself. The manual states: "pairs (t) ... If t has a metamethod
__pairs, calls it with t as argument." I see no way of implementing
your proposal that will not involve a change to "pairs (t[,opt]) ...
If t has a metamethod __pairs, calls it with t and opt as arguments."


I'm going to get it printed on a T-Shirt (or maybe a bumper sticker):

"'pairs' and 'ipairs' are not syntax, dammit!"

'pairs' and 'ipairs' are bog-standard Lua functions and Lua already has perfectly good generic mechanisms for overloading functions. Metamethods for overloading specific functions are unnecessary bloat. Metamethods are only needed to overload syntax, and IMHO should be reserved and restricted for this purpose. If you want to overload 'pairs' for your class, implement your own version as a method and have your users write:

for k, v in instanceofmyclass:pairs() do ... end

If you want to improve this, make the metamethod a proper syntax overload like my '__iter' proposal allowing your users to write:

for k, v in instanceofmyclass do ... end

My proposal does not preclude using the method approach instead (or as well) if you want multiple iterators, and the method approach allows you to parameterise the iterator method any way you want.