lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Mon, Jun 1, 2015 at 1:04 PM, Tim Hill <drtimhill@gmail.com> wrote:
>
> On Jun 1, 2015, at 8:05 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
>
> 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 whether
> the default #tbl is deterministic for the particular table, i.e. whether the
> table has no holes. Being a sequence is merely a sufficient condition. The
> iterations `for i=1,#tbl` and `for i in ipairs(tbl)` both ignore
> non-integer keys.
>
> So I would be tempted to change the function name to "hasnoholes" and
> the 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
>

Tables that "have no holes" are a NECESSARY condition for being a
sequence, but not a SUFFICIENT one.

It is, however, a sufficient condition for use in ipairs/#t/etc.

So in other words, you basically said exactly what Dirk was saying already.

/s/ Adam