lua-users home
lua-l archive

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


On Thu, Dec 16, 2010 at 11:26 AM, Joshua Phillips <jp.sittingduck@gmail.com> wrote:
Perhaps a better idea to solve the '"holes" problem' is to store the
largest number key with each table, so that table.maxn can be O(1),
but adding new number keys would be a little slower.
This will increase the space overhead of each table though, which might
hurt performance elsewhere.

I 100% agree with having a sane version of table.maxn with support built into Lua to track the maxn value, however I would suggest a different approach where table.maxn just returned the maximum integer value which had been used to store a value in the table, therefore:

t={}
t[1000] = nil

Now table.maxn(t) would return 1000

So you couldn't "shrink" a table by setting an element to nil.  In fact setting an index to nil can modify table.maxn since it just tracks the maximum integer index which had been used to store a value (even nil) in the table.  It isn't perfect, but it is O(1), useful, and easy to understand.