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

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

    Here's my take on this, using #array to detect a gap or stop when too many keys have been read:

    function isArray(array)
      local count=0
      for k,_ in pairs(array) do
        count=count+1
        if (type(k) ~= "number" or k < 1 or k > #array or count > #array or math.floor(k) ~= k) then 
          return false
        end
      end
      if count ~= #array then
        return false
      end
      return true
    end
    

提交回复
热议问题