I have a GUI and I'm trying to detect if ANY buttons within a table have been clicked, and then fire a function based on that. Is this the right way to go about it? (I feel like it isn't). Thanks for your help in advance!
frame = script.Parent buttons = {} -- create buttons table for _,v in pairs (frame:getChildren()) do if v:IsA("ImageButton") then table.insert(buttons, v) end end function buttonClicked(button) end --when any button is clicked buttons.Mouse1ButtonClick:connect(buttonClicked())
Tables
buttons
is a table, it doesn't represent a singular object that updates everything inside of it once changed. In fact, you won't even need that table because GetChildren()
already returns one for you. You can just iterate all the objects inside GetChildren() with a for loop, and connect a button to an event within that for loop. Here's an example:
local frame = script.Parent for i,v in pairs(frame:GetChildren()) do -- Let's go ahead and check if the object is a button in the first place if v:IsA("TextButton") or v:IsA("ImageButton") then -- Connect the event to that individual button. v.MouseButton1Click:connect(function() print("Button was clicked") end) end end
This would accomplish what you were describing. Hope this helped, just let me know if you have any questions.
Well, you're right that you're wrong.
buttons
is a list. A list does not have a click event. You want what's inside the list, not the list itself.
Furthermore, buttonClicked()
calls the function and is equal to the result of it. In this case, the result is nil
. You want to connect the function, not the result of the function. buttonClicked
What you need to do is loop through the table and connect an event to each button like so:
for i, button in ipairs(buttons) do button.MouseButton1Click:connect(buttonClicked) end