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

I don't understand parts of this script. What does "_, child in pairs()" mean within a for-do loop?

Asked by
RAYAN1565 691 Moderation Voter
5 years ago
local myModel = script.Parent:FindFirstChild("Model")
local myModelChildren = myModel:GetChildren()

for _, child in pairs(myModelChildren) do
    if child:IsA("BasePart") then
        child.Anchored = true
        child.Transparency = 0.5
        child.Position = child.Position + Vector3.new(1, 0, 1)
    end
end

I have recently posted a question and received an answer but I still do not understand how parts of the script works. In particular, I do not know what _, child in pairs(myModelChildren) means and why the for do loop does not contain the starting value, ending value, and increment. Also, I don't understand what child refers to. Hopefully, someone is able to clear up the confusion I'm experiencing.

1 answer

Log in to vote
0
Answered by 5 years ago

When you use :GetChildren() it returns a table of each individual children, like a dictionary.

The first variable inside of the loop is usually never used so they replaced it with something has has nothing special in it, in this case they use _ for the name of the variable.

The second variable is the name of the value in the table.

In pairs essentially runs the code inside of the loop as much times as how much values the table holds (the amount of children). And since child is a different variable each time its run, like this:

game.Workspace 
- Children:
  - Baseplate
  - Terrain

And if you do

for _, child in pairs(game.Workspace) do
   print(child)
end

--> Output: Baseplate
--> Output: Terrain
1
Thorough answer. Thank you! RAYAN1565 691 — 5y
Ad

Answer this question