Any difference "for k, v in next, t, nil do" and same without nil?

Hi,

I figured out that for k, v in next, t do takes every key from array from 1 to last where:
k - key (2,3,4…)
v - value of key
t - table.

I have seen people sometimes adding nil after table, so it looks like this: for k, v in next, t, nil do

I would like to know what does nil doing there? Is there any difference if i add it or don’t?

I don’t think there’s a difference as nil is automatically passed as an argument if the value is missing anyway.

3 Likes

So if i put nil then every key that don’t have value will be skipped?

Nil means the default will pass through
which is 0 in this case

Edit, check post below

1 Like

The positioning of nil in a next loop can serve as the index in which you are starting the loop. You can read more about this phenomenon here or experiment with it in the Lua demo if you are interested.

For example, if I were to run the following:

for i,v in next,{1,2,3},nil do
print(i,v)
end

I would receive:

1
2
3

But if I ran:

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

The output would be:

2
3

The purpose of using nil in that particular case is to receive all key-value pairs that exist within the table.

5 Likes

Actually nil in next as a key means it’ll the get first key and value. next, {'a', 'b', 'c'}, 0 fails

This is incorrect, on Luau and Lua 5.1 pairs{} == next is false, and on Lua 5.2 and over there’s a __pairs metamethod while next doesn’t have one so saying that it’s equivalent to the pairs function is false:

1 Like

Interesting. It states in the Lua docs that pairs uses the next function as it’s iterator and the function I pulled is straight from their site. I’ll edit my post to reflect what you said.

This is out of my own curiosity unrelated to the topic, but if return next, t, nil doesn’t indicate equivalency, what are the actual differences?

2 Likes