Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What are Anonymous Functions?

Asked by 9 years ago

I heard about them but don't fully understand so what are anonymous functions?Please show example if possible. Thanks!

2 answers

Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
9 years ago

'Anonymous' just means that something has no name. Therefore an anonymous function is a function that has no name.

Normally, we would name a function like this;

function hi() print("hi") end

So an anonymous function is literally just a function without this name.

function() print("hi") end

This is a raw function value, and will just error. It's comparable to just putting a number or string in your code without any context. We need to do something with this value.

It turns out we can do pretty much anything with it, as long as we're giving the anonymous function context.

We can call it;

(function() print("hi") end)()

We can plop it in a table;

t = {function() print("hi") end}

But the way anonymous functions are mostly used is as an argument. When you connect an event, you're connecting it to a function. Whether you use that function's name, or you write an anonymous function, doesn't matter.

script.Parent.Touched:connect(function()
    print("hi")
end)

This is the preferred method of spacing it out. But doing it like the following can help you see exactly what you're doing;

script.Parent.Touched:connect(
    function()
        print("hi")
    end
)

See it now? You're using the anonymous function, which is merely a function value, as the argument.

Ad
Log in to vote
0
Answered by 9 years ago

In simplest terms, an anonymous function is a function that isn't set as a variable.

Example of Chatted connection with named function:

local Chatted = function(Message)
    print(Message)
end
game:GetService("Players").TickerOfTime.Chatted:connect(Chatted)
--// You can still access "Chatted" later

Example with anonymous function:

game:GetService("Players").TickerOfTime.Chatted:connect(function(Message)
    print(Message)
end)
-// No reference to the function now. It's lost
0
How does it affect the game/script? Accelital -7 — 9y
0
These two function the same, but the in the top one, the function can be reused, saving code space. TickerOfTime 70 — 9y

Answer this question