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