Inheritance of metamethods

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Inheritance of metamethods

Dirk Laurie-2
Lua does not support inheritance of metamethods.

I.e. if I have an object with metatable Triple, which contains the
metamethod Triple.__add, and I wish to make a derived class RGB, I can
add two RGB triples by Triple.__add(a,b) or by a:__add(b) (both
because my class system makes a metatable its own __index) but not by
a+b.

When I started typing this post, I was hoping that someone knew a way
around the problem, but I now realize there is a good reason:
Triple.__add would return a new Triple, not a new RGB. So making
access to metamethods raw is there to protect us.

Maybe this whole inheritance business is overrated. Cleaner and
simpler to wrap the object in the new class.

Reply | Threaded
Open this post in threaded view
|

Re: Inheritance of metamethods

Coda Highland


On Mon, Mar 4, 2019 at 4:00 AM Dirk Laurie <[hidden email]> wrote:
Lua does not support inheritance of metamethods.

I.e. if I have an object with metatable Triple, which contains the
metamethod Triple.__add, and I wish to make a derived class RGB, I can
add two RGB triples by Triple.__add(a,b) or by a:__add(b) (both
because my class system makes a metatable its own __index) but not by
a+b.

When I started typing this post, I was hoping that someone knew a way
around the problem, but I now realize there is a good reason:
Triple.__add would return a new Triple, not a new RGB. So making
access to metamethods raw is there to protect us.

Maybe this whole inheritance business is overrated. Cleaner and
simpler to wrap the object in the new class.


I mean, Triple.__add(a, b) could return setmetatable(result, getmetatable(a)) to solve that problem.

/s/ AdamĀ