lua中#,getn, maxn获取数组的长度的陷阱

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HQ354974212/article/details/89374675

lua获取table长度的接口有很多:

  • table.getn()
  • ’#’操作符
  • table.maxn()

#table.getn 等价,它计算的是数组元素长度不包括hash 键值),返回从1开始连续的最大key(看具体情况)。

maxn 不论key是否连续,返回最大的key


 在规范的数组情况下,三种方式都能正常获取值:

t= {
    4,5,6,7,8
}
print("#" ,#t , "getn",table.getn(t) ,"maxn", table.maxn(t) )

t= {
    [1]=4,
    [2]=5,
    [3]=6,
    [4]=7,
    [5]=8,
}
print("#" ,#t , "getn",table.getn(t) ,"maxn", table.maxn(t) )

 


连续的最大key值3

t= {
    [-1]=4,
    [0]=5,
    [1]=6,
    [2]=7,
    [3]=8,
}
print("#" ,#t , "getn",table.getn(t) ,"maxn", table.maxn(t) )


这里需要注意了,两次竟然返回不同6,3 ,而不是4,3 , 比较特殊,请看lua源码实现

t= {
    [1]=4,
    [2]=5,
    [3]=6,
    [4]=7,
    [6]=8,
}
print("#" ,#t , "getn",table.getn(t) ,"maxn", table.maxn(t) )

t= {
    [1]=4,
    [2]=5,
    [3]=6,
    [5]=7,
    [6]=8,
}
print("#" ,#t , "getn",table.getn(t) ,"maxn", table.maxn(t) )


#,getn 只返回数组从1开始连续的最大key,, maxn 返回最大整数key

t= {
    4,
    5,
    6,
    aa=7,
    bb=8,
}
print("#" ,#t , "getn",table.getn(t) ,"maxn", table.maxn(t) )



t= {
    aa=1,
    bb="2",
    [3]=3,
    dd=7,
    ee=8,
}
print("#" ,#t , "getn",table.getn(t) ,"maxn", table.maxn(t) )

猜你喜欢

转载自blog.csdn.net/HQ354974212/article/details/89374675