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

The purpose of pairs? [closed]

Asked by
emite1000 335 Moderation Voter
9 years ago

This question already has an answer here:

What does for _, in pairs mean?

The one thing that I still can't wrap my mind around in scripting is Pairs. Can someone explain to me in the simplest terms possible what the purpose of the Pairs() function is? What is it supposed to do?

I should have clarified I did read through the other answers to this question on this site, but didn't understand them. That's why I asked for a really simple answer (Funyun's was perfect).

0
See  also questions 4, 100, 2633, and countless others you can find by searching. BlueTaslem 18071 — 9y

Marked as Duplicate by BlueTaslem

This question has been asked before, and already has an answer. If those answers do not fully address your question, then please ask a new question here.

Why was this question closed?

1 answer

Log in to vote
2
Answered by
funyun 958 Moderation Voter
9 years ago

The [for i, v in pairs(table) do] loop is called a "generic for" loop. This loop is useful for tables. Basically, [for i, v in pairs(table) do] in English is "For every object in this group of objects, do this stuff". For example, if you have a model with some parts in it, and you want to set each part's transparency equal to .5, you can do this via the generic for loop.

for i, v in pairs(workspace.Model:GetChildren()) do
    if v:IsA("Part") then v.Transparency = .5 end
end

In the generic for loop, i and v are variables that are used within the loop, and nowhere else. "i" is the "key" of the current element, or where it is located in the table. Usually, "i" is useless, and is commonly replaced with "_". "v" is what exactly the element is. In the example, "v" in each iteration of the loop is a part in the model. "i" and "v" can be replaced with whatever variable name you want, such as "noob, lol", "abc, def" or "huUoh, IOJHLUI". GetChildren() is a method of getting a table consisting of objects within the object stated. workspace.Model:GetChildren() returns a table consisting of everything in the model.

In another example, we'll actually make a table and use the generic for loop.

table = {"lol", 1337, "noob", 9001} --Make a table with that stuff in it

for i, v in pairs(table) do --For each thing in the table
    print(v, i) --Print what the element is and where it is in the table respectively
end

That should output "lol 1, 1337 2, noob 3, 9001 4".

Hope that helps.

0
Yes -- pairs literally returns a *pair* of values. Perci1 4988 — 9y
0
Derp. Said I was going to set the transparency to .5, set it to 1 in the script. Oh well. funyun 958 — 9y
Ad