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

What does for i,v in NEXT do? And what can it be used for

Asked by 5 years ago
Edited 5 years ago

I never understood

for i, v in next(Table) do 
print(v)
end

2 answers

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

Iterators

next is a stateless iterator with the signature next(table[, key]) -> key2, value. It's also what is produced by pairs, which is in essence

function pairs(t)
  return next, t 
end

It takes a table and an optional key and produces the 'next' key/value pair in the table, the first pair if you don't supply the optional key, or nil if there's no next key


So how do iterators work?

When you use a for ... in ... do-style loop, the real format of it is

for nextArg, ... in iteratorFunction[, iteratorConstant[, initialArg]] do

And all missing optional inputs become nil. At the start of the iteration, it calls iteratorFunction(iteratorConstant, initialArg), with the returns becoming variables for the loop. Every further iteration it calls iteratorFunction(iteratorConstant, nextArg) until nextArg is nil.


As an aside, your example is not really a correct use of next

Ad
Log in to vote
0
Answered by
2ndwann 131
5 years ago
Edited 5 years ago

It is something called an "Iterator", basically it cycles through a list (the table), to find certain things or get certain contents of it. It is useful for player inventories and things that involve a list of items.

Iterators are usually like

for i=1, 10 do

or just like you said,

for i, v in next(Table) do
print(v)
end

or (this one is perfect for getting the children of a model and changing its properties)

for name, child in pairs(model:GetChildren()) do -- Looping through all of the children
    if child:IsA("BasePart") then -- Checking if it's a part
        child.BrickColor = BrickColor.Red() -- Setting it to red
        child.Transparency = 0.2 -- Transparency
    end
end)

I hope this explanation helps.

Answer this question