lua-users home
lua-l archive

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

On 10/06/2014 01:31, Coda Highland wrote:
On Mon, Jun 9, 2014 at 9:14 PM, Andrew Starks <> wrote:
On Mon, Jun 9, 2014 at 9:25 PM, Thiago L. <> 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

I thought # just used the array size? (you know, with OP_NEWTABLE you have hash size and array size... I thought # just returned that array size...)

Also wouldn't this be faster and behave the same as ipairs: (in 5.1 at least... 5.2 can screw itself for all I care about... also I didn't test or benchmark it...)
local a,b,c = 1,#t,1
local v = t[a]
while a <= b and v ~= nil do
    -- your stuff here
    -- use this as if it is "for a,v in ipairs(t) do <...> end"
    a = a + c
    v = t[a]