WoW:API getn: Difference between revisions

From AddOn Studio
Jump to navigation Jump to search
No edit summary
mNo edit summary
Line 22: Line 22:
   3
   3


It seems things are not quite that simple.
getn and the # operator start at index [1] and count up, ceasing when they reach a nil value. This means that if you have a table
See here for details: [http://lua-users.org/wiki/LuaTableSize Lua Table Size Discussion]
 
Table.getn works as you'd expect if your keys are numeric (i.e. indices).
t = { [0]      = "zero",  --will not be counted
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.
      [1]      = "one",    --will be counted; 1
Quoting from the linked page:
      [2]     = "two",    --will be counted; 2
''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.''
      [3]      = "three",  --will be counted; 3
      ["four"] = "four",   --will not be counted; returns 3
      [5]      = "five" }  --will never be reached
 
running getn(t) or #t will return 3, not the expected 4. Although there are 4 indices, it will count to three, see that t[4] is a blank spot, and return with a count of three. It will never reach 5. Furthermore, keys such as t["four"] and array values less than 1 such as t[0] are not counted at all.


== See Also ==
== See Also ==

Revision as of 03:22, 27 January 2007

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

getn and the # operator start at index [1] and count up, ceasing when they reach a nil value. This means that if you have a table

t = { [0]      = "zero",   --will not be counted
      [1]      = "one",    --will be counted; 1
      [2]      = "two",    --will be counted; 2
      [3]      = "three",  --will be counted; 3
      ["four"] = "four",   --will not be counted; returns 3
      [5]      = "five" }  --will never be reached

running getn(t) or #t will return 3, not the expected 4. Although there are 4 indices, it will count to three, see that t[4] is a blank spot, and return with a count of three. It will never reach 5. Furthermore, keys such as t["four"] and array values less than 1 such as t[0] are not counted at all.

See Also

Template:LUA