lua:获取table的长度

对于一个table来说,要获得其长度,最简单的应该是直接使用“#”操作符。值得注意的是table.getn函数在lua5.+版本已经被移除。
当然,如果table是一个数组,那么长度计算一般是正确的(没有值为nil)

t={
    
    1,2,3,4}
print(#t)
--this will output 4

虽然“#”操作符简单,但是,其计数有时候并不准确。

t={
    
    [-1]=-1,[0]=0,[1]=1,[2]=2,[4]=5}
print(#t)
--this will output 4
t={
    
    [-1]=-1,[2]=1}
print(#t)
--this will output 0
t={
    
    a=1,b=2}
print(#t)
--this will output 0

所以,如果我们计算table,最好自己写一个函数

function length(t)
    local res=0
    for k,v in pairs(t) do
        res=res+1
    end
    return res
end

t={
    
    2,3,4,5}
t[2]=nil
print(#t) --this will output 4
print(length(t)) --this will output 3, because t[2] was deleted

猜你喜欢

转载自blog.csdn.net/watqw/article/details/124112321
今日推荐