Getting the button that was clicked from Activated event

hi, this seems like an easy issue but I can’t seem to find the solution.

Is there any way to get the button that was clicked from an activated event?

I know this can be accomplished with something like this:

local buttonTable = script.Parent.Something:GetChild()
local function OnClick()
	
	for i, v in ipairs(buttonTable) do
		local thisButton = v
		thisButton.Activated:Connect(function() 
			-- do something with "thisButton", for example turn its highlight off 
			end
		)
	end
end

However I would like to pass in a function when connecting to the Activated event instead. It is more of a coding style preference.

local buttonTable = script.Parent.Something:GetChild()

local function AnotherFunction()
	-- do something with thisButton, for example turn its highlight off 
end

local function OnClick()
	for i, v in ipairs(buttonTable) do
		local thisButton = v
		thisButton.Activated:Connect(AnotherFunction)
	end
end

Is there a way to acccomplish the above? It doesn’t seem like it is possible to pass in a variable to the connected function, nor is it possible to get the button from the inputObject variable from an activated event.

1 Like

You can have AnotherFunction return a function. This is called a closure.

local function AnotherFunction(thisButton)
    --// return a function so the Activated signal has something to connect to
    return function()
        --// this functions inherits the scope defined above it; aka the parameters of AnotherFunction
        --// do something with thisButton
    end
end

local function OnClick()
	for i, v in ipairs(buttonTable) do
		local thisButton = v
        local newFunction = AnotherFunction(thisButton) --// new function

		thisButton.Activated:Connect(newFunction) --// connect it
	end
end

This returns a function that has a reference to the thisButton passed to it. Then connects that returned function to the Activated signal.

4 Likes

I think something like this is overkill, perhaps OP should explain why they want to do this (other than preference). With your example OP is still doing what they don’t want to do because you are returning a new function each iteration

That worked! Thanks a bunch!

In response to @sjr04, my other use case was to pass a master button to a utility module to make sure there are enough copies of this button in a grid.

If there isn’t enough buttons, it will clone the master button and create the connections for the activated event of all cloned buttons.

With the above solution, I could pass the function to the utility module to create the connections if needed.