How can I create a function that inserts an item into a table when a GUI is clicked, with atleast 60 GUIs can be clicked?

Lets say I have a table.

local Table = {}

GUI1.MouseButton1Down:Connect(function()
       table.insert(Table, GUI1.TextLabel.Text)
end)

This script does the job of adding an item to that table when a GUI is clicked.

GUI1.MouseButton1Down:Connect(function()
       table.insert(Table, GUI1.TextLabel.Text)
end)

GUI2.MouseButton1Down:Connect(function()
       table.insert(Table, GUI2.TextLabel.Text)
end)
GUI3.MouseButton1Down:Connect(function()
       table.insert(Table, GUI3.TextLabel.Text)
end)
GUI4.MouseButton1Down:Connect(function()
       table.insert(Table, GUI4.TextLabel.Text)
end)

This script also does the job, but it is long.

What im asking is, is there a way to shorten the script above ?

I have LOTS of GUIs that can be clicked and can add an item to the table. Copy pasting that funciton over and over again will make the script atleast 600 lines long, not counting the other code in the script. So this isn’t an option. I tried searching for something that might help but I didn’t find anything.

I was originally thinking I can find out which GUI was clicked, and connect each GUI to a function. But I’m not too sure I can do that.

If it is possible to see which GUI was clicked, it could solve the script. If anybody knows a solution, please help !

Thanks for your time ! :smiley:

Could you not just loop through a list of guis and then listen for mousebutton1down?

for i,v in pairs(guiContainer:GetChildren()) do
    if (v:IsA("GuiButton")) then
        v.MouseButton1Down:Connect(function()
            table.insert(Table, v.TextLabel.Text)
        end)
    end
end
5 Likes

Perhaps make a function:


function RegisterButton(Button)
    Button.MouseButton1Down:Connect(function() -- I'd recommend using MouseButton1Click here ;)
           table.insert(Table, Button.TextLabel.Text)
    end) 
end

RegisterButton(GUI1)
RegisterButton(GUI2)
RegisterButton(GUI3)
RegisterButton(GUI4)

I’d also recommend looping through the GUI Container, as @Nucl3arPlays suggested, with his imperative solution.

2 Likes