lua-users home
lua-l archive

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


local function setlength (t, len)
  local mt = getmetatable(t) or {}
  setmetatable(t,mt)
  mt.__len = function () return len end
end

^ Sean, are you referring to this type of solution? I am sure it would cover some bases.

The other solutions I can think of are:
1. Using pairs to find the largest numerical index of a table (slow to get length, but allows nil within the table)
2. Overriding __newindex to keep track of a max value. This enables 't[1000] = true' to cause '#t = 1000'. Could get hairy with removing values.


On Thu, Jul 16, 2020 at 3:40 PM Sean Conner <sean@conman.org> 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?

  -spc