在 Lua 中,咱們能夠經過這個符號」#「 來計算字符串的長度和一個table的長度,好比:html
str = "I'am a string!"
print(#str) => 14less
一般這個#符號也能夠用來計算一個 Table 的長度,好比:函數
t = {1, 2, 3, 5, 100}
print(#t) => 5luat = {1, 2, 3, 5, {}, 100}
print(#t) => 6code
上面兩個例子都很好理解,再來看一個:htm
t = {1, 2, a=3, 5, {}, 100}
print(#t) => 5字符串
這裏 a=3 不能算是sequence序列的一個成員,因此a=3並無被統計進去,再來看看這個列子:get
t = {1, 2, a=3, nil, 100}
print(#t)string
這個你們能夠試試,個人lua版本是5.2 輸出結果是 4it
t = {1, 2, a=3, nil}
print(#t) => 2
能夠看到,當sequence中有nil的時候,這個結果就有點很差理解了,若是nil也被統計進長度,那麼上面的例子輸出應該是3而不是2,若是不統計那麼倒數第二個例子應該是輸出3而不是4,這是爲何呢?
先來看看 Lua 5.1 對 這個#操做的定義,這個定義能夠寫的不是很好理解,可是也能看出來#對lua table的單目操做是定義在這個table裏全部成員都是非nil的前提下,Lua 5.2的定義更容易讓人明白,引用:
A program can modify the behavior of the length operator for any value
but strings through the __len metamethod (see §2.4).Unless a __len metamethod is given, the length of a table t is only
defined if the table is a sequence, that is, the set of its positive
numeric keys is equal to {1..n} for some non-negative integer n. In
that case, n is its length. Note that a table like{10, 20, nil, 40} is not a sequence, because it has the key 4 but does not have the key 3. (So, there is no n such that the set {1..n}is equal to the set of positive numeric keys of that table.) Note,
however, that non-numeric keys do not interfere with whether a table
is a sequence.
能夠看到,相似{10, 20, nil, 40}這樣的table並不能定義爲一個sequence,天然#符號對這個table的操做就是無效的,未有定義的,若是必定要計算這樣的table或者處理table中有a=2 這樣的非sequence元素的時候,則須要本身修改metatable來定義__len這個函數實現自定義的處理方法,這個下次再說。
由於這個緣由業務上吃了大虧,記錄下修改代碼去了