lua-users home
lua-l archive

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

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

Essentially we allow the length operator to be used in an lvalue (we
can already invoke functions in lvalues, so this is not
unprecedented). If I understand the implementation correctly, the
length will not be altered unless the table is reindexed, which only
happens if we make a lot of insertions to the hash-map. If this is
still too volatile, there could be a flag similar to `isrealasize(t)`
that doesn't allow the size to shrink if it was set this way. If
necessary for semantic consistency, doing this could also set t[5] =
false when otherwise t[5] = nil.

This also speeds up the creation of large arrays. Previously you had to do this:

t = {}
for i = 1, 10000 do t[i] = false end

During that loop the array would be reallocated several times. With
length assignment (`#t = 10000`) you get *one* reindex. Much nicer.