table 尺寸差异。两个例子都一样吗?

table size difference. are both examples identical?

tNum={[2]=true , [3]=true,[4]=true, [5]=true ,[6]=true }

#tNum-->0 



tNum={} 
tNum[2]=true 
tNum[3]=true 
tNum[4]=true 
tNum[5]=true 
tNum[6]=true

#tNum-->6 

为什么大小相差这么大? 两个例子是否相同?

问题是,当您将 table 定义为从索引 [2] 开始时,长度运算符会中断,因为它假定 tables 从索引 [1] 开始. 以下代码按预期工作:

tNum = {[1]=false, [2]=true, [3]=true, [4]=true, [5]=true, [6]=true}

#tNum => 6

奇怪的行为是因为当你用tNum={}初始化一个数组时,它通过将每个索引分配给nil来初始化,第一个索引是[1](它实际上并没有初始化每个值为零,但这样更容易解释)。 相反,当您使用 tNum={[2]=true} 初始化数组时,您明确告诉数组 tNum[1] 不存在 并且数组从索引 2 开始。长度计算中断当你这样做的时候。

有关更详尽的解释,请参阅底部附近 lua wiki 的 this section,其中解释了:

For those that really want their arrays starting at 0, it is not difficult to write the following:

days = {[0]="Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday"}

Now, the first value, "Sunday", is at index 0. That zero does not affect the other fields, but "Monday" naturally goes to index 1, because it is the first list value in the constructor; the other values follow it. Despite this facility, I do not recommend the use of arrays starting at 0 in Lua. Remember that most functions assume that arrays start at index 1, and therefore will not handle such arrays correctly.

Length 运算符假设您的数组将从索引 [1] 开始,因为它不是,所以无法正常工作。

希望对您有所帮助,祝您代码顺利!

你的两个表在语义上是相同的,但是在它们上面使用 # 是不明确的。 0 和 6 都是正确的长度。这里是 an abridged version of the docs:

The length operator applied on a table returns a border in that table. A border in a table t is any natural number that satisfies the following condition:

(border == 0 or t[border] ~= nil) and t[border + 1] == nil

A table with exactly one border is called a sequence.

When t is not a sequence, #t can return any of its borders. (The exact one depends on details of the internal representation of the table, which in turn can depend on how the table was populated and the memory addresses of its non-numeric keys.)

这是未定义行为 (UB) 的示例。 (这可能不是正确的词,因为行为是部分定义的。Lua 中的 UB 不能像在 C 中那样发射核武器。)未定义的行为很重要,因为它给了开发者自由选择尽可能最快的算法,而不必担心当用户违反他们的假设时会发生什么。

要找到长度,Lua 最多进行 log n 次猜测,而不是查看每个元素以找到明确的长度。对于大型阵列,这会大大加快速度。