How can I check if a lua table contains only sequential numeric indices?

前端 未结 7 2193
时光取名叫无心
时光取名叫无心 2021-02-06 06:07

How can I write a function that determines whether it\'s table argument is a true array?

isArray({1, 2, 4, 8, 16}) -> true
isArray({1, \"two\", 3, 4, 5}) ->         


        
7条回答
  •  时光说笑
    2021-02-06 06:41

    I wrote this code for another similar question lately:

    ---Checks if a table is used as an array. That is: the keys start with one and are sequential numbers
    -- @param t table
    -- @return nil,error string if t is not a table
    -- @return true/false if t is an array/isn't an array
    -- NOTE: it returns true for an empty table
    function isArray(t)
        if type(t)~="table" then return nil,"Argument is not a table! It is: "..type(t) end
        --check if all the table keys are numerical and count their number
        local count=0
        for k,v in pairs(t) do
            if type(k)~="number" then return false else count=count+1 end
        end
        --all keys are numerical. now let's see if they are sequential and start with 1
        for i=1,count do
            --Hint: the VALUE might be "nil", in that case "not t[i]" isn't enough, that's why we check the type
            if not t[i] and type(t[i])~="nil" then return false end
        end
        return true
    end
    

提交回复
热议问题