I have a GUI with buttons and a function that fires whenever any of the buttons are clicked. However, the function doesn't seem to be returning any data about the actual particular button that was clicked. Is there a way to make this work?
01 | local frame = script.Parent |
02 |
03 | --script errors at the print function because button never actually exists |
04 | function buttonClicked(button) |
05 | print (button.Name .. " was clicked!" ) |
06 | end |
07 |
08 | for i,v in pairs (frame:GetChildren()) do |
09 |
10 | -- Let's go ahead and check if the object is a button in the first place |
11 | if v:IsA( "TextButton" ) or v:IsA( "ImageButton" ) then |
12 |
13 | -- Connect the event to that individual button. |
14 | v.MouseButton 1 Click:connect(buttonClicked) |
15 |
16 | end |
17 | end |
What you're referring to is a callback. This is basically a way to have a function call another function, while passing arguments to the function it's calling. This is extremely useful in a lot of specific cases. Here would be an example in your scenario:
01 | local frame = script.Parent |
02 |
03 | --script errors at the print function because button never actually exists |
04 | function buttonClicked(button) |
05 | print (button.Name .. " was clicked!" ) |
06 | end |
07 |
08 | for i,v in pairs (frame:GetChildren()) do |
09 |
10 | -- Let's go ahead and check if the object is a button in the first place |
11 | if v:IsA( "TextButton" ) or v:IsA( "ImageButton" ) then |
12 |
13 | -- This makes it so once the button is clicked, it will call |
14 | -- 'buttonClicked', while also passing the argument 'v' |
15 | -- to it, which is the button. |
Hope this helped, let me know if you have any questions.