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

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

    EDIT: Here's a new way to test for arrays that I discovered just recently. For each element returned by pairs, it simply checks that the nth item on it is not nil. As far as I know, this is the fastest and most elegant way to test for array-ness.

    local function isArray(t)
      local i = 0
      for _ in pairs(t) do
        i = i + 1
        if t[i] == nil then return false end
      end
      return true
    end
    

提交回复
热议问题