I have always written functions like option 1.
However, I realised there is another way and maybe it is even better performance wise.
These are two scripts doing the same, but I’m unsure which one is the best option.
Option 1: Using the function
local part = script.Parent
part.Touched:Connect(function()
print("test")
-- the rest of what should happen on touch
end)
Option 2: Calling the function
local part = script.Parent
local function functionname()
print("test")
-- the rest of what should happen on touch
end
part.Touched:Connect(functionname)
- ‘‘the rest of what should happen on touch’’ → assume multiple things happen
- the script is used many times in this scenario
Would option 2 be better? I think so, but this is my question as I’m not sure. I was wondering.
Thanks in advance!
For what is worth, this has been asked before. The answer though is mostly style. Use option 2 if you need to call the function in more than one place. Option 1 is referred to as an “anonymous function” because it doesn’t have a variable or a name assigned to it. They are available in most programming languages, though sometimes called Lambda Functions after the terminology in calculus, and there is still nothing wrong with them unless you don’t like the style.
2 Likes
Oh! I searched for topics on this, but couldn’t find one… sorry for that.
I do have a question though.
Everytime the part is being touched, the function runs. In option 2, the function is already ‘‘known’’ to the script and in option 1, it just runs the script as usual. Does the script run through the variable again and again in option 2 every time it is touched? If yes, is that the better option?
Edit: thank you for the detailed answer @JarodOfOrbiter, I will use option 2 from now on
You mean like it creates a new function every time? No. Not unless you’re actually connecting the event again every single time, but even then it shouldn’t create a new function. If I remember right, all the static data such as “Hello World!”, tables, functions, and numbers and such already exist even at the top of the script. They just don’t get assigned to any variables until the script reaches that line. So your function exists even before you reach that line. Every time that line is executed it should use the same function.
You’re right by the way, I just did a search and it’s really difficult to find anything relevant. I know it’s been answered before, but I suppose that doesn’t mean you can find it. It helps that most people asking this don’t know to call it an anonymous function.
1 Like
Very helpful! I appreciate it. Thank you very much!
1 Like