The official documentation describes it#as follows: The length operator is written as the unary operator #. The length of a string is its number of bytes (that is, the length of a string calculated as one byte per character).
The length of a table t is defined as an integer index n. It satisfies that t[n] is not nil and t[n+1] is nil; in addition, if t
local tblTest2 =
{
1,
a = 2,
3,
}
print(table.getn(tblTest2))
What is the output of this code? The output here should be2. First, you need to understand that this ctblTest2c is not a simple ctable; it mixes two styles: list and record. In the table,a = 2it is in record style. Secondly, you need to understand that a record-style record is not counted in the length calculation of the outer table. You can think of it as a function; just as in other object-oriented languages, functions are not recorded as internal variables.
Since it is like a function, you can output the value of a, yes.print(tblTest2.a)That's all.
Now look at the following code:
local tblTest3 =
{
1,
{a = 2},
3,
}
print(table.getn(tblTest3))
What is the output of this code? The output here should be3. Note that a table nested in a table is also an element. Therefore, the output is3。
table.getn(t)is equivalent to#t。
The following case is quite confusing; you can directly read the summary in the last sentence:
Now let's look at a rather confusing one:
local tblTest4 =
{
1,
nil,
}
print(table.getn(tblTest4))
What is the output of this code? It is 1. We all know that when a table gets its length, it traverses the entire table and returns at the last non-nil value.
But what about the following code?
local tblTest5 =
{
1,
nil,
2,
}
print(table.getn(tblTest5))
It outputs 3. Fun, right? It counts nil as an element when calculating the length. But the one that really baffles you is the following code:
local tblTest5 =
{
1,
nil,
2,
nil
}
It outputs 1. Here's another snippet to completely confuse you:
local tblTest5 =
{
1,
nil,
2,
nil,
3,
nil
}
It outputs 3. Confused? Look again; this section will make you never dare to write nil values in a table from now on:
local tblTest5 =
{
1,
nil,
2,
nil,
3,
nil,
4,
nil
}
Take a look, the output of this section is 1. Dear, do you still dare to use nil values in Lua tables in the future??? If you keep adding nil afterward, you might discover something. You may think you have found a pattern. But you must never think this is a pattern. Because it is wrong.
- 1. Do not use nil in tables.
- 2. If you really must use nil, you have to use the table.setn() function to set the length of the table. Note: Newer versions of Lua no longer support setn.
We must give you a conclusion:The setn function is obsolete. Do not use nil values in Lua tables. If an element needs to be deleted, just remove it; do not replace it with nil.
Source: http://www.cnblogs.com/youxin/p/3799339.html