lua-users home
lua-l archive

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


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.

--Leo--