Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

The purpose of pairs?

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).

1 comment

0

See  also questions 4, 100, 2633, and countless others you can find by searching.

1 answer

✓ Accepted answer

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.

2 comments

0

Yes -- pairs literally returns a pair of values.

0

Derp. Said I was going to set the transparency to .5, set it to 1 in the script. Oh well.

This discussion is preserved as it was. New answers, comments, and votes are closed.