Do event-triggered functions have to be anonymous?

I recall when I was doing scripting work on models years ago, it was possible to fire functions utilizing events from something like a ClickDetector which would look something like this:

function IO_Yes()
	--Code
end

YesB.ClickDetector.MouseClick:connect(IO_Yes())

When “connect” was deprecated to make way for the newer “Connect”, I noticed that the method of firing a function displayed above does not work anymore. It would have to fire from an anonymous function like this:

YesB.ClickDetector.MouseClick:Connect(function()
	--Code
end)

Problem: If I tried writing a function like the first example with the newer “Connect”, it would not work and would return the following error message in my output: “Attempt to connect failed: Passed value is not a function”. I had realized that the field inside the parentheses :Connect() is asking for is the function itself, not the name of a function which is actually a void datatype, hence why the error message describes that the passed value is not a function.

Questions: So does that mean I can only connect events only to anonymous functions or is there a way to connect an event to a named function? And if the functionality of connecting events to named functions has been totally taken out after the deprecation of the old “connect”, is there good reasoning behind why that happened?

I kind of see one good and one bad thing if it was truly removed; firing a function with an event like in the second example would make the method shown in the first example overly redundant and unnecessary. If you can fire a function through an event like MouseClick from a ClickDetector, there’s no need to have it named since it isn’t being called within the script. However, this could pose a problem if I wanted to fire a function in multiple methods, through both an event connection and through a typical calling in a script.

1 Like

Spoiler: all functions in Lua are anonymous. There is no concept of a named function in Lua.

f() is not the same as f.

When you do event:Connect(f()) you are calling the function f and passing its return value to :Connect. Simply remove the parentheses and it will work. event:Connect(f). The deprecation of :connect is irrelevant here; this has never worked with the latter.

3 Likes

Thank you so much for pointing that out. I know it’s something people will get into once in a while but I always make stupid mistakes like that. I believe I tried doing that before but assumed that it caused a syntax error since I had erased one parenthesis for Connect so I went back in my loop of turmoil and anger. What I meant by “named function” was just the name that goes after function (e.g. function onTouch()).

2 Likes

That isn’t a name tho.

function onTouch()

end

is the same as

onTouch = function()

end

It’s still unnamed. :+1:

2 Likes