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

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

    Note: as @eric points out, pairs is not defined to iterate in a specific order. Hence this is no valid answer.

    The following should be sufficient; it checks that the keys are sequential from 1 until the end:

    local function isArray(array)
      local n = 1
      for k, _ in pairs(array) do
        if k ~= n then return false end
        n = n + 1
      end
    
      return true
    end
    

提交回复
热议问题