Search code examples
arraysdictionarylualua-table

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


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}) -> true
isArray({1, [3]="two", [2]=3, 4, 5}) -> true
isArray({1, dictionaryKey = "not an array", 3, 4, 5}) -> false

I can't see any way of finding out if the numeric keys are the only keys.


Solution

  • 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 == numIndices
    end
    

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