Re[2]: Some conservative Lua metamethod extension proposals
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re[2]: Some conservative Lua metamethod extension proposals
- From: "John Hind" <john.hind@...>
- Date: 2018年3月25日 10:48:58 +0000
From: "Tim Hill" <drtimhill@gmail.com>
Sent: 24/03/2018 17:20:46
On Mar 24, 2018, at 2:45 AM, John Hind <john.hind@zen.co.uk> wrote:
'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.
While meta methods for pairs/ipairs might indeed be overkill, I
disagree that this is always the case. Take tostring() for example.
Would you advocate removing __tostring()? I would argue this is a bad
idea. Sure, I can write some kind of tostring() over-ride, or create
one for each type of object, but that doesnt help in large projects
where I might not have control of (or even access to) all the code
using tostring() to generate output.
The fact is, in larger projects, polymorphic/generic functions are
indeed very useful, and metamethods are one way to create these.
Arguing that pairs() should not have a meta method because “it’s just a
Lua function” doesnt seem to me much of an argument. You are better
arguing that ipairs() is DEFINED as iterating over all positive numeric
indices in order until a nil is returned, which IS a valid argument
against __ipairs meta method (which could break this contract).
—Tim
You open up another objection: Lua's true syntax metamethods extend but
do not override the language specification. So by this logic, __pairs
should only work for userdata. You really argue against yourself in your
last sentence, because __pairs and __tostring (as currently specified)
could also be used to 'break the contract' in the same way (for example
a __pairs override might hide elements in the table). As for __tostring,
probably that should work at the syntax level i.e. it would apply
anywhere there is a coercion from anything to string. And why not
__tonumber?
There is possibly an argument for having crude 'dump anything' or 'print
anything' functions in the debug library, so for example:
for k, v in debug.pairs(anyrandomvariable) do debug.print(v)
which would be guaranteed not to generate an exception for any variable
thrown at them. These might have extend-only metamethods for userdata.
-John