Is there any way to send a Function trough a BindableEvent?

What I want to do is to make an alert box that you can select yes or no, if you select yes I want a function to run. But I can’t get the function through the BindableEvent.

I’ve tried to do:

local alertFunction = function() print("test") end game:GetService("ReplicatedStorage").Events.MakeAlert:Fire(alertFunction())

And also:

game:GetService("ReplicatedStorage").Events.MakeAlert:Fire(function() print("test") end)

And the script that gets the Event looks like this:

--// Make Alert
local function MakeAlert(alertFunction)
	if alertFunction ~= nil then
		alertYesNo.YesButton.MouseButton1Click:Connect(alertFunction)
	else
		warn(":: Make Alert :: No function was given!")
	end
end



--// Function Calls
makeAlert.Event:Connect(MakeAlert)

But they don’t seem to work. So I wonder if there is any solution to this.

In the :Fire() part, change “AlertFunction()” to “AlertFunction” (no brackets). When you include the brackets, what you’re doing is telling the script to run the function (not to send it thru the event as a variable). When you do it without brackets, you are referring to the function as a variable, so in that case it should be able to be passed through a BindableEvent

That does not work, I just get this error in the output:

Exception caught in TGenericSlotWrapper. Attempt to load a function from a different Lua VM

You can’t pass functions.

The proper practice would be to use an existing bindable or a module and if your function needs to do different things then you pass arguments to parameters.

Well, technically…

local function AlertFunction(alertMessage)
	if alertMessage ~= nil then
		print(alertMessage)
	end
end

game:GetService("ReplicatedStorage").Events.MakeAlert:Fire(function() alert("test") end)
local function MakeAlert(alertFunction)
	if alertFunction ~= nil then
		alertYesNo.YesButton.MouseButton1Click:Connect(alertFunction)
	else
		warn(":: Make Alert :: No function was given!")
	end
end

makeAlert.Event:Connect(MakeAlert)

I am not sure I wouldn’t go insane using them this way, and goodness knows if it’s proper. But hey, it does answer the question.

1 Like

Not sure if you read my post correctly, but I found a solution to this by using a module like @MrNicNac said.

How I did it:

local module = {}

--// The function that needs to be run
function module:Run()
    print("test")
end

return module

And the alert script looks like this:

--// Make Alert
local function MakeAlert(title, description, alertType, alertModule)
	if alertModule ~= nil then
		alertYesNo.YesButton.MouseButton1Click:Connect(function()
			local alertFunction = require(alertModule)
			alertFunction:Run()
        end)
	else
		warn(":: Make Alert :: No AlertModule was given!, AlertModule = " .. alertModule)
	end
end



--// Function Calls
makeAlert.Event:Connect(MakeAlert)
1 Like