lua-users home
lua-l archive

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


On Wed, Mar 12, 2008 at 3:23 PM, Eva Schmidt <es@sol-3.de> wrote:
> Hello guys,
>
>  I've got a question on the Lua table structure:
>
>  In case of numerical table indices I can use the length operator # to get the
>  number of fields. With one restriction: indices must be incremental without any
>  gaps because the definition is:
>  "... any integer index n such that t[n] is not nil and t[n+1] is nil ..."
>
>  For tables with string indices there is simply no length operator :-(
>
>  So far, the only way to get a reliable information about the length of a table
>  is to iterate it by using for i,v in pairs (tbl) and count the field by myself.
>
>  For me this is very dissatisfying. :-(
>
>  Is there any way to find a length operator for tables independent of the type of
>  its keys?

If you find yourself needing this, you have two options:

1.) Wrap all assignment to the table (including setting to nil) in a
function call that updates an internal counter.  Then your inserts and
removes have extra overhead but you can query the length of the table
with virtually no cost.

2.) Iterate the table using pairs() and update the count when you need
it.  This is expensive when you have a large table, but saves you from
the insert/remove overhead.

There is no native way to cheaply determine the number of key/value
pairs in a Lua table.

- Jim