lua-users home
lua-l archive

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


On Jun 15, 2014, at 3:02 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:

> 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.
> 

So the logic is, table sort() may have complex semantics when metamethods are used, so table.unpack() should not use metamethods?

First, there is a big difference between the two: one mutates the table the other does not. Second, I find your example contrived. The table.sort() function has defined semantics (comparing and swapping values). If the caller has constructed a metatable that means those sort semantics have a specific, albeit unusual, effect, then that’s the effect they have; caveat emptor. It should be noted that in your example table.sort() has equally peculiar behavior when used with raw get/set as well. Are you then arguing that table.sort() should be removed from the library entirely?

The Lua docs are full of elegant ways to use metamethods with tables, many involving various forms of information hiding and abstractions. I do find it odd that, having expounded on their use, the standard Lua library then bypasses them most of the time. Particularly as, has been noted, they can be constructed in a way that has insignificant performance impact.

Regardless, my original point stands: the stated justification for not using metamethods on table.unpack(), that of performance, does not appear to be the case.

—Tim