lua中 table.getn(t) 、#t、 table.maxn(t) 這三個什么區別?
RT
local t = {1,888,x= 999,b=2,5,nil,6,7,[10]=1,8,{z = 1,y = 1},nil,nil}
print(table.getn(t))
print(#t)
print(table.maxn(t))
輸出:8 8 8
------------如果把[10] =1 改成[11] =1 那么輸出8 8 11 這又是為什么?
local t = {1,888,x= 999,b=2,5,nil,6,7,[10]=1,8,{z = 1,y = 1},nil,nil}
print(table.getn(t))
print(#t)
print(table.maxn(t))
輸出:8 8 8
------------如果把[10] =1 改成[11] =1 那么輸出8 8 11 這又是為什么?
1個回答
==1==
table.getn(t)
等價於 #t
但是它計算的是數組元素。不包括hash 鍵值。
而且數組是以第一個nil元素來判斷數組結束。
#只計算array的元素個數,它實際上調用了對象的metatable 的__ len函數。
對於有__len 方法的函數返回函數返回值。不然就返回數組成員數目。
==2==
a={1,3,a='b',[6]='six',['10']='ten'}
a 和 [6] ['10']是作為hash保存的。#a => 2 他是不包括hash成員的計數。
1 3 是 數組結構保存的。table.maxn(a) => 6
因為a中所有元素最大的數值索引是6不是字符串10
.你的代碼返回11 是因為它是最大的數值索引。
maxn lua 5.2 已經拋棄了,不過依然可以使用。
table.getn(t)
等價於 #t
但是它計算的是數組元素。不包括hash 鍵值。
而且數組是以第一個nil元素來判斷數組結束。
#只計算array的元素個數,它實際上調用了對象的metatable 的__ len函數。
對於有__len 方法的函數返回函數返回值。不然就返回數組成員數目。
==2==
a={1,3,a='b',[6]='six',['10']='ten'}
a 和 [6] ['10']是作為hash保存的。#a => 2 他是不包括hash成員的計數。
1 3 是 數組結構保存的。table.maxn(a) => 6
因為a中所有元素最大的數值索引是6不是字符串10
.你的代碼返回11 是因為它是最大的數值索引。
maxn lua 5.2 已經拋棄了,不過依然可以使用。
更多追問追答
追問
但是它計算的是數組元素。不包括hash 鍵值。
而且數組是以第一個nil元素來判斷數組結束。
=========這個意思不就是說get(n)只會計算到第一個nil就停止么,但是我上面的例子好像沒有停止,
追答
a={1,3,a='b',[6]='six',['10']='ten'}
a 和 [6] ['10']是作為hash保存的。#a => 2 他是不包括hash成員的計數。
這句話我說的有點誤會。其實數組的數據結構也是hash。lua中數組的意思是:table的元素擁有連續的數字索引。比如:{[1]=1,[2]=2,[3]=3}
The length operator is denoted by the unary prefix 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).
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 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.
上面這句話是手冊里的內容。
table的長度是 table為序列時的某個n 使得,{1..n} == table的所有數字索引。也就是說序列的數字索引必須連續。
# 運算得到的length 只針對 序列有意義 。當table不是序列時length 沒有明確含義。
table中間包括nil,這個table就不是序列,例如:
a={10, 20, nil, 40}
它不是序列,因為他的數字索引是 1 2 4 不是連續的,所以它不是序列。
所以 #a 得到的值並不能准確反映table的元素個數。
手冊的意思是說 針對非序列使用#,而那個table又沒有__len 時它值無意義的。
再給你個實例:
a={1,2,3,4,5}
print(#a)
5
a[2]=nil
print(#a) --此時a已經不是序列,此時對數列使用# , 具體意義不明。
5
a[5]=nil --刪除最后元素
print(#a) --看看 結果。
1
===
對於你想刪除某個序列的元素,必須使用 table.remove 而不是 a[n]=nil