lua中#,getn, maxn获取数组的长度的陷阱
了解网络诈骗中常见的数字陷阱 #生活技巧# #工作学习技巧# #数字技能提升#
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) )
网址:lua中#,getn, maxn获取数组的长度的陷阱 https://www.yuejiaxmz.com/news/view/231581
相关内容
小心移动支付领域三大“陷阱”十大陷阱专坑上帝消费者
实施流程自动化和人工智能:最佳实践与应避免的陷阱
10个饮食误区曝光 你是否有陷入营养“陷阱”?
小家电维修谨防三大陷阱
怎样避开家电维修陷阱
存钱成瘾?8万背后的病态节俭,如何避免陷入金钱陷阱
汽车美容陷阱多 消费者需明白花钱
邱丽丨警惕“科学育儿”陷阱
什么品牌的空气净化器最好用呢?四大空气净化器选购陷阱别中招!