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

what does next do?

Asked by 10 years ago

what does the next function do so if you have like for i,v in next do(variable) ~~~~~~~~~~~~~~~~~ what would that do?

1 answer

Log in to vote
1
Answered by
jakedies 315 Trusted Moderation Voter Administrator Community Moderator
10 years ago

The next variable holds a function that helps you iterate over tables. The pairs function actually uses the next function to iterate over a table. Also next does not go in any specific order and takes a key to get the next key.

local myTable = {a = 5, b = 6};
local key1, value1 = next(myTable);
local key2, value2 = next(myTable, key1);
print(key1, value1, key2, value2);

--[[Possible outputs:
a 5 b 6
b 6 a 5
]]

The reason there are 2 possible outputs is because next can't go in some kind of order. You are not guaranteed order when you use next, but without next there wouldn't be a way to iterate over table with non-numerical keys.

So let's see how this works in a loop:

local myTable = {a = 5, b = 6};
for key, value in next, myTable, nil do
    print(key, value);
end

On the first iteration, the key used (second argument of next) is nil So you can rewrite the loop like this:

for key, value in next, myTable do

And after the first iteration, it uses the key returned from the first iteration and uses it as the key (second argument for next) in the second iteration.

Ad

Answer this question