[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Why do we have ipairs?
- From: Coda Highland <chighland@...>
- Date: Mon, 9 Jun 2014 21:31:01 -0700
On Mon, Jun 9, 2014 at 9:14 PM, Andrew Starks <firstname.lastname@example.org> wrote:
> On Mon, Jun 9, 2014 at 9:25 PM, Thiago L. <email@example.com> wrote:
>> Last I checked, `for x,y in ipairs(t) do` is slower than `for x=1,#t do
>> local y = t[x]`, so why do we have ipairs()?
> In 5.2, __len and __ipairs made that a easy answer: you can override them
> independently. In 5.1, someone else might have a better answer than i.
# isn't a constant-time operation -- it's O(log n) in the size of the
table. Furthermore its behavior is only well-defined for a proper
sequence, wherein the table contains no nil-valued entries with
integer keys less than the greatest integer key with a non-nil value.
ipairs(), meanwhile, stops at the first nil value encountered in the
table. Semantically, ipairs() is the more well-defined behavior.
Ultimately, it's the semantic behavior that gives ipairs() its value
-- not because it's faster, but because its use parallels the behavior
of pairs() and any other iterator function defined.