no edit summary
mNo edit summary |
No edit summary |
||
| Line 26: | Line 26: | ||
> print( #{1,2,3} ) | > print( #{1,2,3} ) | ||
3 | |||
However, it does not always behave as one might expect. Consider the following sequence: | |||
> t = { 1, 2, 3 } | |||
> dump (#t) | |||
3 | 3 | ||
> t[1] = nil | |||
> dump (#t) | |||
3 | |||
t | > dump (t) | ||
{ | |||
[2] = 2 | |||
[3] = 3 | |||
} -- table: 0x807ff70 | |||
> dump (#{ [2] = 2, [3] = 3 }) | |||
0 | |||
As you can see, the # operator is unpredictable in that it can return different values for tables with identical contents. The Lua 5.1 reference manual has this to say about it [http://www.lua.org/manual/5.1/]: | |||
The length of a table t is defined to be any integer index such that t[n] is not nil and t[n+1] is nil. | |||
In other words, be careful with this operator if you are using tables with holes in them. If your table has all its values between [1] and [n] for some n, with no nils in that range, the # operator will return n. Otherwise its result may be unclear. | |||
== See Also == | == See Also == | ||