How pass parameter from event to function

local function ChoiceSelected(parent)
	Arrow.Parent = parent -- ERROR
	Arrow.Visible = true
end

Choice1.MouseEnter:Connect(ChoiceSelected)

(Object expected, got number)

1 Like

Please refer to the documentation on MouseEnter. The event gives two parameters, x and y, both numbers and neither are objects.

Is there a way for me to pass Choice1 then? Because what I had originally was

Choice1.MouseEnter:Connect(function()
	choiceSelected(Choice1)
end)

Choice1.MouseLeave:Connect(function()
	choiceUnselected()
end)

Choice2.MouseEnter:Connect(function()
	choiceSelected(Choice2)
end)

Choice2.MouseLeave:Connect(function()
	choiceUnselected()
end)

Which just feels way too clunky

1 Like
local function hookEvents(choice)

	choice.MouseEnter:Connect(function()
		choiceSelected(choice)
	end)

	choice.MouseLeave:Connect(function()
		choiceUnselected()
	end)
	
end

hookEvents(Choice1)
hookEvents(Choice2)
5 Likes

If you want, you can use an HOF (higher ordered function). A hof is a function that returns a function and/or takes a function as an argument.

Like

local function ChoiceSelected(parent)
    return function()
        Arrow.Parent = parent -- ERROR
        Arrow.Visible = true
    end
end

event:Connect(ChoiceSelected(parent))

And this will pass the returned function to :Connect

11 Likes
local function ChoiceSelected(parent)
	Arrow.Parent = parent 
	Arrow.Visible = true
end

Choice1.MouseEnter:Connect(function()
       ChoiceSelected(Choice1)
)

so it will pass the object that fired the event, not the event parameters.

2 Likes

The MouseEnter Event by design takes 2 parameters, the x and y position of the mouse. You are trying to replace that parameter with an object Instance that you named as a parent. The only time you’re going to be able to use that syntax to connect functions is when your local function has the same parameters. For example

local function ChoiceSelected(x,y)
-- bla bla bla
end

Choice1.MouseEnter:Connect(ChoiceSelected)

in order to make your function work, you need to connect the event to an anonymous function, then call the function from that.

Choice1.MouseEnter:Connect(function()

ChoiceSelected(parentParameterHere)
end
1 Like

Hi! I realise I’m a little late to the party but for anyone reading this, looking for an answer, you could accomplish this with two functions as @IsaacFantasy and @ADRENALXNE suggested but in a compact way as seen below:

Choice1.MouseEnter:Connect(function(x, y) ChoiceSelected(x, y, parent) end)
1 Like