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

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

    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.

提交回复
热议问题