lua-users home
lua-l archive

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


> Question 3:
>
> It seems like there is no quick way to determine the number key-value
> pairs in an associative table (short of iterating through and counting
> them all).  If I am not missing something, why is there no quick way
> to determine the number of key-value pairs in an associative table?
>
> Perhaps the C implementation of Lua counts the number of pairs as they
> are added and removed, but this count is not exposed in Lua?
>
> Or does the C implementation not even count the number of pairs in a
> table?  If not, why not?  This would seem to be a very useful number
> to have quick access to.

Using metatables, I'd imagine this would be easy to implement. The __newindex method is provided to catch new entries to the table, which is where you count new entries. I'd go a step further and memoize a function that returned these counts, and use the table itself as a key in the memoization.