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

前端 未结 7 2190
时光取名叫无心
时光取名叫无心 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:44

    By "true array", I suppose you mean a table whose keys are only numbers. To do this, check the type of every key of your table. Try this :

    function isArray(array)
        for k, _ in pairs(array) do
            if type(k) ~= "number" then
                return false
            end
        end
        return true --Found nothing but numbers !
    end
    
    0 讨论(0)
提交回复
热议问题