1. 程式人生 > >關於lua table.getn()和#

關於lua table.getn()和#

在lua中table是強大的資料組合型別,但是因為強大所以有些地方使用會不好理解。
table可以是list:local list_table = {1, 2, 3}
table可以是dict:local dict_table = {a=1,b=2}
table可以是連結串列:local lb_tale={value = 1, next=nil}
當然table也可以混合。

lua5.0之後版本table.getn()被廢棄,可使用#.

但是有個問題是在獲取table的長度的時候:

2.5.5 - The Length Operator
The length operator is denoted by the unary operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).
The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has “holes” (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).

所以在有需要獲取長度的table中儘量不要使用混合table,並且不要設定nil。如果你設定nil,你需要手動去修改table的長度table.setn()

雖然我們可以通過設定某個元素為nil來達到刪除這個元素的目的,但是直接進行設定會帶來獲取長度的問題,可以使用table.remove(index)來刪除,但是這個方法還是有很多侷限的。
如果想避免遇到莫名的麻煩,儘量讓你的table更簡單。