table在删除元素时要注意,例
t = { "hello", "world", "!"}t[1] = nil此时print(#t) --输出3,就是说把表的元素置为nil并没有移除该表项。但,若是:
t = {[1] = nil,[2] = 223,[3] = nil}function count(t) local c = 0 for k, v in pairs(t) do c = c + 1 end return cendprint(count(t))--1
再看更诡异的
1 t = { 2 [1] = 12, 3 [2] = nil, 4 [3] = 4 5 } 6 7 function count(t) 8 local c = 0 9 for k, v in pairs(t) do10 c = c + 111 end12 return c13 end14 15 print("------------------", #t)16 t2 = { "hello", "world", "!"}17 t2[1] = nil18 t2[22] = nil19 t2[9] = nil20 print("--------t2---------", #t2)21 for k, v in pairs(t2) do22 print(k, v)23 end24 25 print("--------------->")26 for i=1, #t2 do27 print(i, t2[i])28 end