lua-users home
lua-l archive

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


+1

While incurring the risk of being labeled flamebait, this is the kind
of discussion around #t that I think makes sense.

On 12/15/10, Keith Matthews <keith.l.matthews@gmail.com> wrote:
> In the lua-5.2.0-alpha manual, at the beginning of section 6.5 - Table
> Manipulation, it says:
>
> "when we talk about the "length" of a table we mean the result of the
> length operator"
>
> In the definition for the length operator, it says:
>
> "A program can modify the behavior of the length operator for any
> value but strings through metamethods"
>
> Therefore, I expect table.insert, table.remove, table.sort,
> table.concat and table.unpack to honor the __len metamethod on tables,
> since their description says that they work over the table length.
>
> Yet, it doesn't work as documented:
>
>> t = setmetatable({}, { __len = function(t) return 3 end })
>> t[1], t[2], t[3], t[4], t[5] = "e", "d", "c", "b", "a"
>> = #t
> 3
>
> So far, so good; the length operator respects the length metamethod.
>
>> =table.concat(t)
> edcba
>
> I expected only the first 3 strings to be concatenated (edc)
>
>> table.sort(t)
>> for i = 1, 5 do io.write(t[i]) end
> abcde
>
> I expected only the first 3 elements to be sorted (cdeba).
>
>> print(table.unpack(t))
> e	d	c	b	a
>
> I expected to see only the first 3 strings:
> e	d	c
>
> Table.insert and table.remove don't respect the __len metamethod either.
>
> In ltablib.c, I noticed that these functions called lua_rawlen instead
> of lua_len. After changing them, I got the behaviour I expected.
>
> I'm not sure if the bug is in the manual or in ltablib.c, but the
> language seems more self-consistent when the functions in the table
> module respect the __len metamethod.
>
> - Keith
>
>