[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Metamethods: fallbacks or overrides?
- From: Coroutines <coroutines@...>
- Date: Sun, 17 Aug 2014 19:10:02 -0700
On Sun, Aug 17, 2014 at 10:42 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> Originally, metamethods were called "fallbacks". The first name
> change, to "tag methods", came with Lua 3.0. In Lua 5.0, the
> name in the manual was changed to "metamethods", but "tag
> methods" still appears the code (ltm.h).
>
> The idea, in the words of Roberto [1], is that:
>
> In general, arithmetic metamethods are only called when
> Lua "does not know what to do".
>
> I.e. these metamethods are fallbacks. You no longer get an error,
> you get the result of the metamethod.
>
> In Lua 5.2, metamethods were introduced that are more like
> overrides. Lua does know what to do, but you can tell it to
> something else.
>
> __len: preferred to the built-in code for the # operator
> __pairs: preferred to the standard library "pairs" function
> __ipairs: preferred to the standard library "ipairs" function
>
> Lua 5.3.0-alpha removes __ipairs, so it seems at this stage
> that overrides is not a preferred direction for future Lua
> development.
>
> [1] <http://lua-users.org/lists/lua-l/2012-06/msg00246.html>
>
Hmm I was thinking about starting a thread like this, good on you :-)
In that other thread where I was talking about adding other
__metamethods, I was imagining something very clean where the function
to add 2 numbers together wasn't hidden in the C side of Lua, but
accessible through debug.getmetatable(0).__add
I was imagining that it would be very organized and (reflective?) to
be able to get at and modify how primitives operate. Some people
would rather have operations that create NaN shoot out an error,
rather than return NaN -- if we could wrap the operations allowed
between numbers we could do this. I feel like in this way it would be
simpler to modify Lua into a DSL without having to touch any C. At
the same time I recognize that by connecting these underlying C
functions to metamethods exposed to Lua it would slow Lua down (I
haven't done any benchmarks but I'm pretty certain).
On an unrelated note: __pairs and __ipairs are not necessary to be
upstream -- I wish they were so it promotes an interface everyone
knows about, but you can just wrap ipairs() and pairs() of course.
I'm sad to see __ipairs go, I feel like we went back a step.