How can I create a table for the children inside of the parent so that whenever I needed to find when the child is clicked, the things that I want to store inside of the child will only be inside of the specific child and does not move to a different child whenever I clicked onto another child?
for i,button in ipairs(Buttons) do
button.MouseButton1Click:connect(function()
end)
end
What is the difference between ipairs and pairs?
The important takeaway from @KreatorKols is the fact that you can connect the clicked event from inside the loop, and then access the button upvalue as normal.
Put another way, if you had this hierarchy:
PlayerGui
|- LocalScript
|- TextButton -- Text = "First"
|- TextButton -- Text = "Second"
`- TextButton -- Text = "Third"
You could have each button print out its Text field like this:
local parent = script.Parent
local children = parent:GetChildren()
for _, button in pairs(children) do
-- use button as the current button inside this loop
if button:IsA("GuiButton") then
button.MouseButton1Click:Connect(function()
print("Button text: " .. button.Text)
end)
end
end
In this case, nothing. Generally, ipairs only iterates through indices 1..n, and does so in order:
local t = {[1] = 'a', [2] = 'b', [3] = 'c', [5] = 'd', asdf = 'e'}
for k, v in pairs(t) do print(k, v) end
print("---")
for k, v in ipairs(t) do print(k, v) end
--[[
3 c
2 b
asdf e
5 d
1 a
---
1 a
2 b
3 c
]]