lua-users home
lua-l archive

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


On Mon, Jun 9, 2014 at 9:14 PM, Andrew Starks <andrew.starks@trms.com> wrote:
>
> On Mon, Jun 9, 2014 at 9:25 PM, Thiago L. <fakedme@gmail.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.

/s/ Adam