  lua-l archive

• Subject: Re: Testing for a sequence (was Re: Lua 5.2 Length Operator and tables (bug?)
• From: Petite Abeille <petite.abeille@...>
• Date: Thu, 19 Apr 2012 19:17:15 +0200

```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

```

• Follow-Ups:
• References: