lua-users home
lua-l archive

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


On Apr 19, 2012, at 8:28 AM, Dirk Laurie wrote:

> I do it this way:
> 
> function is_seq(aTable)
>   local count=0
>   local nmax=-1
>   for k in pairs(aTable) do
>      n=tonumber(k)

<-- typo? Global n?

>      if n and n%1==0 and n>0 then
>          count=count+1; nmax=math.max(nmax,n)
>      end
>    end
>    return nmax==count
> end
> 
> BTW, why does the definition of a proper sequence exclude {}?
> The table functions and length operator work properly in that case too.

It doesn't have to. Whatever floats your boat.

In practice, defining an empty table as a sequence or not is not really helping either way though. More like hair-splitting :P


P.S.

FWIW:  HasSequence vs. IsSequence

local function HasSequence( aTable )
  local hasSequence = false

  for aKey in pairs( aTable ) do
    if type( aKey ) == 'number' and aKey > 0 and aKey == math.floor( aKey ) then
      hasSequence = true

      if aTable[ math.max( aKey - 1, 1 ) ] == nil then
        return false
      end
    end
  end

  return hasSequence
end

local function IsSequence( aTable )
  for aKey in pairs( aTable ) do
    if not( type( aKey ) == 'number' and aKey > 0 and aKey == math.floor( aKey ) and aTable[ math.max( aKey - 1, 1 ) ] ~= nil ) then
      return false
    end
  end

  return true
end