ipair iterates over indices 1..n, where n + 1 is the first index with a zero value
pairs are repeated on all keys.
if there are more keys than consecutive indexes, then this cannot be an array.
So all you have to do is see if the number of elements in pairs(table)
equals 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 new to Lua, so there may be a built-in function to reduce the calculations of numKeys and numIndices for simple function calls.
Ponkadoodle
source share