lua-users home
lua-l archive

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


On Tue, Jan 4, 2011 at 2:01 AM, David Manura <dm.lua@math2.org> wrote:
>> [...] table.pack() might want a metatable where __len returns the larger
>> of n and the raw length [to be read by table.unpack]
>
> That would break the current practice that table.* functions ignore metamethods.

I was basing this off of
http://lua-users.org/lists/lua-l/2010-12/msg00653.html,
though on rereading, this post is probably just promising a
documentation fix, and I misread it.

>> The standard library probably needs a rawlen() function [...]
>
> Nor is there, for that matter, rawtostring, rawipairs, and rawpairs
> [2], although rawipairs and rawpairs (and to some extent rawlen) can
> be implemented in terms of rawget and next (not called "rawnext").

I'd go farther and say that __pairs and __ipairs pretty much never
want to be written in terms of pairs() and ipairs().  These two
functions are only interesting in terms of the iterator function they
return, which you probably want to replace.  In any event the
originals are easy to get to even in the face of __pairs and __ipairs,
the latter by (ipairs({})).

I think it's worth emphasizing that things really happened the way I
said they did.  It wasn't that I felt rawlen() was needed for
consistency reasons; I set out to write what I thought was a
reasonable metamethod and quickly realized it couldn't be done.  Even
though the metamethod I was trying to write was misguided, there
probably still are cases where __len wants access to the underlying
table's primitive length.  A metamethod for tables that returns t.n if
n is present, and #t otherwise, feels genuinely useful.  But to do
that, __len needs access to the table's primitive length, very much
like __newindex needs raw access to t[k]=v, and in a way __pairs does
not need raw access to pairs().

Greg F