lua中匪夷所思的table长度


s = { 1, 2, 3, 4, 5, 6 }
print(#s)     -- output: 6
s[4] = nil
print(#s)     -- output: 6
s[7] = nil
print(#s)     -- output: 3
s[4] = 4
print(#s)     -- output: 6
s[4] = nil
print(#s)     -- output: 3

print()

s = { "1", "2", "3", "4", "5", "6" }
print(#s)     -- output: 6
s["4"] = nil
print(#s)     -- output: 6
s["7"] = nil
print(#s)     -- output: 6
s["4"] = "4"
print(#s)     -- output: 6
s["4"] = nil
print(#s)     -- output: 6

Lua 5.3.4

输出就是这么匪夷所思,所以, 不要在Lua的table中使用nil值,如果一个元素要删除,直接remove

Author: honmaple

NO CONTENTS

lin.jiang

风落花语风落天,花落风雨花落田.