What is the point of custom functions?

I see stuff like this used a lot:

local function onInputBegan(input, gameProcessed)
    --Code
end
 
UserInputService.InputBegan:Connect(onInputBegan)

Apparently it’s “good practice,” but to me it seems like it just makes things unnecessarily complicated.

I would much rather use this:

UserInputService.InputBegan:Connect(function(input, gameProcessed)
    --Code
end)

I also don’t like how devhub uses the custom function method every time, so I get really confused, but then I scroll to the bottom and find out that it’s a custom function.

It could be useful if you plan to connect the same function to multiple events.

3 Likes

^^, basically let’s say you need to run a function each time a head shows up in workspace, first you would have to run through all already existing heads in workspace and run this function, then create a event for newly made ones. So basically you have this function if that’s the case. And if you want to change something… Well it becomes a drag, also makes your code look neater.

This is actually really great practice if you’re doing a large scale project or plan to use something more than once. Functions is a great way to keep your code a lot less cluttered and a lot more organized. It might seem useless if your only using it once but if you plan on using it multiple times or even just use it for simplicity you’ll notice that your code will most likely end up being smaller.

As an example I made a OTS camera script and created a Enable() and Disable() function so now if I want to enable the OTS camera I can simply type Enable() and saves a ton of lines, and saves a lot of scrolling time. This is great for multiple developers to be able to read your code.

1 Like

It improves reusability and readability. Oftentimes, anonymous functions contribute to large and unreadable function blocks. Generally speaking, the smaller your logical blocks of code are, the easier it will be to understand and maintain.

3 Likes

Go one further and put it in a module script :stuck_out_tongue:

3 Likes
local Players = game:GetService("Players")

function PlayerAdded(Player)
    print(Player.Name)
end

Players.PlayerAdded:Connect(PlayerAdded)
for _, Player in ipairs(Players:GetPlayers()) do
    PlayerAdded(Player)
end

this can be useful when using PlayerAdded

Occasionally, albeit very rarely, you want to connect a function to an event but also have the control of running it whenever you please. That’s when you would define a function as a variable rather than use an anonymous one.

I think most people would connect anonymous functions to Signals just because it’s clearer what the function does.

If you do use a “custom function” connected to a Signal you should name it “onEventName” (e.g. onPlayerAdded)

The only reason for not using anonymous function is if you want to connect and disconnect a function a bunch of times I guess.

1 Like