lua-users home
lua-l archive

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

2014-06-15 1:09 GMT+02:00 Andrew Starks <>:

> Ahh. Your/Dirk's point is that next behaves the same as unpack behaves the
> same as rawgeti, etc. Presumably, "where would the madness end...?"

The extreme example is table.sort. You want to respect __index, right?
What about __newindex? That too?

So let's say a and b are tables with holes in, and both of them have table
c, which has no holes, as fallback. Never forget that "metamethod" is an
educated word for "fallback".

Case 1: a and b have c for both __index and __newindex. Sort a. The sorted
table ls still spread between a and c like a piano tune running between white
and black keys in the same slots. Some stuff that used to be in a is now
in b, and vice versa. Sort b. Does a stay sorted? Probably not.

Case 2: OK, forget about respecting __newindex. Sort a. It's filled up quite
a lot. The black keys that are left still contain what they had before.
That's nice. Really? Would you like to predict in advance which they are?
Not so easy, is it?

> `next` *is* different. It is the only "function" that does something that is
> magic.
> There are many other examples where the standard libraries don't respect
> metatables. I have varying degrees of dislike for all of them, except next.

Well, we share this much: I, too, love using next. In fact, I don't use pairs
any more. `next` saves me a pair of parentheses (nasty things, they need

My opinion is this: in cases where a metamethod might be respected or
not, the library routine should do that which is more often needed. If that
decision is not obvious, it should do that which is less neatly done in
plain Lua. Whenever the __index metamethod is involved, tbl[i] is neater
than rawget(tbl,i). Therefore the library function should be using rawget,
unless it can be argued convincingly that this is the unusual case.