What does the "for" in i,v pairs even do. you don't need it for the loop to function

yeah so I’ve known that you can get rid of the “for” in a i,v iterator loop but what purpose does this really serve I’ve tested around a little and found no use case for removing the “for” keyword in pairs heck you can even put i,v in a variable if you really want to .just seems like syntax sugar to me or whatever you call it. you can chop the statement up and it still seems to function the same code that i made with this concept below

local i,v = pairs(game.Workspace:GetChildren()) do
for x = 1,#v do
warn(v[x])
end
end

–this works the same as a typical for i,v loop but looks off you can even use next here
–so basically how does this work and why does it not just give an error

1 Like

The example you’ve written looks like this:

local i, v = pairs(workspace:GetChildren())

do
   for x = 1, #v do
       warn(v[x])
   end
end

pairs returns an iterator function (next) as it’s first result and the table itself as its second result.

local iteratorFunction, iterationTable = pairs(t)

You’ve essentially just did a normal numeric loop:

local t = {3, 4, 5}
for i = 1, #t do
   print(i)
end

This is the same as

for index in t do
   print(index)
end

Which ever one you use just depends on what you need to do

3 Likes

You may be interested in Chapter 7 of PIL which discusses the internals of iterators (pairs) and the generic for: Programming in Lua : 7

1 Like

wait hold up how does this work i completely removed pairs() and it still works this code I’ve created confuses me so much

for _,v in game.Workspace:GetChildren() do
print(v)
end

for _,v in {5,10,15,20} do
warn(v)
end

That’s called generalized iteration and is the best way to do loops as of late. It uses an algorithm which is sort of pairs and ipairs combined.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.