lua-users home
lua-l archive

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




On Mon, Mar 4, 2019 at 4:00 AM Dirk Laurie <dirk.laurie@gmail.com> 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