lua-users home
lua-l archive

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


On 20/02/2008, Greg Falcon <veloso@verylowsodium.com> wrote:
> On 2/20/08, John Hind <john.hind@zen.co.uk> wrote:
> > Reading Roberto's "Programming in Lua" 2nd Edition, I was struck by the
> >  inconsistency between the String library and the Table library - in Lua 5.1
> >  the former's functions can be used as methods on a String object while the
> >  latter can only be used as "traditional" library functions.
> >
> >  Of course the reason is that Strings have one per-type metatable while Table
> >  metatables are per-instance. There is currently no way for the Table library
> >  to set a metatable for all Tables.
>
> No, the reason you can't do this is that my_table:sort() is syntactic
> sugar for my_table['sort'](my_table).

It occurs to me that, in a sense, tables actually can have type
metatables. Not for all tables, and it's not automatic, but for tables
that are created using any of the available OOP mechanisms that Lua
supports (which of course means explicitly setting the metatable for
each instance of that type, but that is neatly hidden away in the
object creation function/method/macro/whatever).

In other words, tables that represent objects of a certain type
(class/prototype/whatever) have a type metatable. If you need a type
metatable for (almost) all your tables, then you can make a
(base)class or prototype and create all those tables as "instances" of
that type. This way, you can have your type metatable, and still let
regular tables just be regular tables.

I don't think you'd ever need or want automatic type metatables for
all tables. Firstly, metatables are themselves tables, so that would
be a problem. And secondly, it could have unexpected results for
tables created/used in/by libraries and 3rd-party code (one of the
reasons for that was mentioned above by Greg).