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

• Subject: Re: pairs and ipairs
• From: Tom Sutcliffe <tomsci@...>
• Date: Sun, 22 Oct 2023 10:29:45 +0100

```I think the edge cases make it difficult to usefully define. What should something like this do?

{ [1] = "a", [2] = "b", [4] = "d", a = true }

This table is not a sequence, because of the 'hole' between 2 and 4, but ipairs is well-defined to return 1 and 2, so should kpairs include 4? Should all integers be excluded even if they aren't currently part of what ipairs would return? Should kpairs be the exact logical opposite of what ipairs returns, or can there be keys which neither would return? Could one actually implement any definition in a way that didn't require an extra O(N) time and/or space operation?

More concretely, only the caller really knows the intended semantics of any given table. The definition of sequence currently used by Lua carefully carves out one specific type (and only for one specific operation, the len operator) while imposing as few restrictions on any other usage as possible, and there is no definition of what constitutes a "record" key. Intuitively we might think it's obvious, but only because we have a specific usage of table in mind, and there would need to be a definition which both accounts for corner cases, and is sufficiently general to be of use to others whose usage of table might be ever so slightly different.

As another example, the code you suggested would include string keys convertible to integers, which would not be part of the sequence, which just highlights the fact that there are a lot of subtleties in attempting to come up with a meaningful definition :)

Cheers,

Tom

> On 22 Oct 2023, at 09:52, Hans van der Meer <havdmeer@ziggo.nl> wrote:
>
> This question might have come up earlier, but I have not seen it. Thus I dare to ask.
>
> With ipairs() a table is walked through the array sequence in the table.
> With pairs() all elements are visited while traversing the table, the sequence as well as the records.
> However, sometimes I need to visit the record keys only, leaving the elements of the sequence out.
> Of course I can do:
> for k,v in pairs(t) do
> if not tonumber(k) then ... end
> end
>
> 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.
>
> If I am wrong I will gladly hear it.
>
> yours sincerely
> dr. Hans van der Meer
>
>
>

```