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

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

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

✓ Accepted answer

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 comment

1

Thorough answer. Thank you!

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