WoW:API getn

From AddOn Studio
Revision as of 02:01, 18 December 2006 by WoWWiki>WoWWiki-Krag
Jump to navigation Jump to search

Lua/Libshortcut From TableLibraryTutorial of lua-users.org.

table.getn(table)

This is used to determine the size of a table. The size of a table is discussed at the top of this page.

> = table.getn({1,2,3})         -- Lua will count the elements if no size is specified
3
> = table.getn({1,2,3; n=10})   -- note, n overrides counting the elements
10
> t = {1,2,3}
> table.setn(t, 10)              -- set our own size with setn()
> = table.getn(t)
10
> = table.getn({1,2,3,nil,5,6}) -- sequence ends at element 3 due to nil value at 4
3

Note that Lua 5.1 supports the use of the # operator. #t is syntactic sugar for table.getn(t)

 > print( #{1,2,3} )
 3

It seems things are not quite that simple. See here for details: Lua Table Size Discussion Table.getn works as you'd expect if your keys are numeric (i.e. indices). if your table has keys of other type, table.getn might give you back 0 regardless of how many key-value pairs you've stored in the table. Quoting from the linked page: If the table has an n field with a numeric value, this value is the size of the table. Otherwise, the size is the largest numerical index with a non-nil value in the table.

See Also

Template:LUA