Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

For loops with 'next' (is it a function call)?

Asked by
LuaQuest 450 Moderation Voter
8 years ago

This question is based off my observation with using the for loop, with the next function. I know the loop is written in this format:

for i,v in next, {} do
    print(i,v)
end

But why aren't we calling the next function? Why are we using a comma, followed by what should be it's first argument? We do that with pairs and ipairs:

for i,v in pairs({}) do -- calling pairs()
    print(i,v)
end

-- and...

for i,v in ipairs({}) do -- again, calling ipairs()
    print(i,v)
end

-- but then...?
for i,v in next, {} do -- not calling next? 
    print(i,v)
end

So why isn't it written as:

for i,v in next({}) do -- you'd think this would be correct, but it's not.
    print(i,v)
end

If anyone can help me with this, I'd very much appreciate it. Thanks.

1 answer

Log in to vote
2
Answered by
BlackJPI 2658 Snack Break Moderation Voter Community Moderator
8 years ago

The reason we do not call the next function (which takes two arguments, the table and a key) is because the generic for loop actually doesn't require a function at all.

The for loop in Lua requires 3 things after the in keyword which are: an iterator, a table, and the start value.

When you write for i, v in next, {} do, what you are actually saying is for i, v in next, {}, nil do.

next is a primitive Lua function that acts as the iterator, looping through the table given, {} is of course the table, and there is no start value as next does not operate using indices but rather by looking at all values and their keys.

pairs is actually exactly equivalent to using next in a for loop as pairs is defined as follows:

function pairs (t)
    return next, t, nil
end

Knowing all of this, we could also write an equivalent for ipairs in Lua:

function iter (a, i)
    i = i + 1
    local v = a[i]
    if v then
        return i, v
    end
end

function ipairs (a)
    return iter, a, 0
end

We could then call the for loop as for i, v in iter, {}, 0 do and it would iterate through all values starting at index 1 until it hit an index with a nil value, just like ipairs.

Ad

Answer this question