• Subject: Re: pairs and ipairs
• From: Francisco Olarte <folarte@...>
• Date: Sun, 22 Oct 2023 13:27:52 +0200

```On Sun, 22 Oct 2023 at 11:51, Hans van der Meer <havdmeer@ziggo.nl> wrote:
> I am well aware of the fact that the proposal of a kpairs(0 has some limitations and pitfalls.

A huge limitation is you did not even propose it fully:

"But why isn't there a kpairs() for the record keys? I think it would
make some programs easier, especially where the relevant pairs()
function is passed to another function."

You did not define "record keys". People are assuming you meant
"string keys", but a lot of things, even the same table, can be
present as keys.

> Thus for example a key "3" entered in the table as that string belongs to the hash part of the table and should therefore appears in a native kpairs() traversal. That obviates the problem with tonumber(key) in my post. (hmmm, better perhaps testing type(key) instead of tonumber).
> Holes in the array part I do not see as a problem. Everything in the array part (in a sequence or not) should in my proposal be left out of a kpairs(0 traversal.

Remember you have numbers in the hash part, like 0. And ipairs is not
iterating the array part, just try

> a={nil,2,3,4,5,6,7,[0]=0}
> for i,v in ipairs(a) do print(i,v) end

> Limiting kpairs() to the keys in the hash storage of the table exclusively and excluding everything in the array part, does seem a usable definition in my view.

May be having apairs() to will make more sense, but anyway, due to how
they work ( returning values plus a function ) building a Xpairs
functions is easy,  just do it:

> function inext(t,i) i=i+1 ; v=t[i]; if v then return i,v end end
> function zpairs(t) return inext, t, -1 end -- like ipairs, but start at 0.

You can trivially iterate through the string only:

> function snext(t,k)
>>  local v; k,v=next(t,k)
>>  while k~= nil do
>>    if type(k)=="string" then return k,v end
>>    k,v = next(t,k)
>>  end
>> end
> function spairs(t) return snext, t, nil end
> a={1,2,b=3,[{}]=4,c=5,6,7}
> for i,v in spairs(a) do print(i,v) end
b    3
c    5

Francisco Olarte.

```