lua-users home
lua-l archive

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


On Tue, Sep 22, 2009 at 11:28 AM, Leo Razoumov <slonik.az@gmail.com> wrote:
> On 9/21/09, GrayFace <sergroj@mail.ru> wrote:
>> Length operator ignores __index metamethod. This way it is fast and
>> predictable. It also ignores __len metamethod of tables and strings, again,
>> this makes it predictable and faster - for tables and strings it has a
>> definite meaning which cannot be altered.
>> [..snip..]
>
> "Programming in Lua" book (PiL) strongly encourages idiom t[#t+1]=v to
> append new value to a table. In this idiom  t[i] uses meta-methods for
> index resolution while #t ignores them entirely. This could cause very
> hard to find bugs.
>
> function foo(tbl, val)
>  tbl[#tbl+1]= val
>  return tbl
> end
>
> If tbl is a regular table without meta-methods foo works as expecting
> and appends val to the end of tbl. If, on another hand, as a tbl one
> passes a table that has metatable with __index and __newindex set as
> follows
> a={11,22,33}
> tbl= setmetatable({}, {__index=a,__newindex=a})
>
> foo(tbl, "AA") will override the value a[1] instead of appending.
>
> I do not see how can one remedy the situation.
> As you rightfully pointed out, __len meta-method is ignored for tables.

This has been recognised as an oversight, and is expected to change in
5.2 - Roberto posted a list of things early last year that had already
been implemented for it [1] that included:

- tables and strings respect __len metamethod

[1] http://lua-users.org/lists/lua-l/2008-02/msg00720.html

-Duncan