function issequence (t) local n = #t local c = 0 -- count keys in [1..n] for k in pairs(t) do if type(k) == 'number' and k > 0 then if k ~= math.floor(k) or k > n then return false end c = c + 1 end end return c == n end
The right question is not whether a table is a sequence, but whetherthe default #tbl is deterministic for the particular table, i.e. whether thetable has no holes. Being a sequence is merely a sufficient condition. Theiterations `for i=1,#tbl` and `for i in ipairs(tbl)` both ignorenon-integer keys.So I would be tempted to change the function name to "hasnoholes" andthe loop body to if type(k) == 'number' and k > 0 and k==math.floor(k) then if k > n then return false else c=c+1 end end
No, Roberto is using “pairs()” to scan all keys (including non-integral). So it does work as intended and will exclude a table with a positive non-integral key. Tables that “have no holes” are a sufficient condition for being a sequence, which is a more strict definition that determines predictable behavior for # as well as many table library functions.
—Tim
|