Functions are declared in two ways.
One is with named functions:
function name(args)
end
This declares a name to be a function.
The other is anonymous functions (so called because they don't have names). You just don't include the name in the defition. It doesn't declare anything, but makes a function value -- it is not a full statement.
Name functions are just
name = function(args)
end
--they set a variable to an anonymous function.
Thus these two things are the same:
function lightOnFire (part)
print("Going to light this part on fire:")
print(part.Name)
fire = Instance.new("Fire")
fire.Parent = part
end
lightOnFire = function(part)
print("Going to light this part on fire:")
print(part.Name)
fire = Instance.new("Fire")
fire.Parent = part
end
Since lightOnFire is only used in firePart.Touched:connect(lightOnFire) it's pretty easy to replace lightOnFire with the anonymous function, based on what lightOnFire was assigned to:
firePart.Touched:connect(function(part)
print("Going to light this part on fire:")
print(part.Name)
fire = Instance.new("Fire")
fire.Parent = part
end)
In general it's not a good idea to use anonymous functions for events. It prevents you from using the function elsewhere.
If you wanted to make your fire spread, for instance, that would be a problem.
It also makes the function not have a name, so you lose some of the intent behind connecting it in the first place. When you read your code as it was, it's clear that "when part touches firePart, lightOnFire".
It is a little briefer, so if you're sure the function is not necessary to be called, then go ahead and make it anonymous if you want.[^1]
[^1]: You're rarely sure. As an example, PlayerAdded events. Even though there's little reason you would need them outside of the actual event, for testing in Solo you have to invoke the function on objects that were already there -- meaning you have to double the function pointlessly, or just give it a name!
1 comment
The function I gave you, I dont understand how to use them. I would like for you to give me a link to understand how to use that type. Thanks!