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

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


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 trueend


ipairs iterates over indices 1..n, where n+1 is the first integer index with a nil value
pairs iterates over all keys.
if there are more keys than there are sequential indices, then it cannot be an array.

So all you have to do is see if the number of elements in pairs(table) is equal to the number of elements in ipairs(table)
the code can be written as follows:

function isArray(tbl)    local numKeys = 0    for _, _ in pairs(tbl) do        numKeys = numKeys+1    end    local numIndices = 0    for _, _ in ipairs(tbl) do        numIndices = numIndices+1    end    return numKeys == numIndicesend

I'm pretty new to Lua, so there might be some builtin function to reduce the numKeys and numIndices calculations to simple function calls.


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