lua-users home
lua-l archive

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

> What happens if the __len metamethod is overridden?

Good question! The best idea I have is to treat this like __index and add a __setlen metamethod. Length assignment on any non-table value (userdata eg) would then be a type error unless there is a __setlen metamethod defined for that value. Of course the __setlen metamethod then calls for a rawsetlen() function which only works on tables.

You can't currently implement this behavior in pure Lua — you need to change the internal representation of the table to get the speedup. What I wanted was to set the length of the array segment. If there is a __len metamethod, the programmer must ensure their code makes sense, but it's true in that case `#t = 5` does not guarantee the truth of `#t == 5`. 

It seems like this should mean that if the table length is set downwards, all entries between the old (raw) len and new len are deleted. (Hence we may also want `rawgetlen()`, although that is already a question raised by __len). 

On Thursday, July 16, 2020, Sean Conner <> wrote:
It was thus said that the Great Mason Bogue once stated:
> We are all generally aware of the issues with the length operator on
> tables containing nil. There was an idea to fix this in 5.4 by
> creating a special t[x] = undef syntax, which was considered too ugly.
> Here I propose an alternative:
> #t = 5 -- sets the length of the array portion of t to 5

  What happens if the __len metamethod is overridden?