I heard about them but don't fully understand so what are anonymous functions?Please show example if possible. Thanks!
'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.
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