So I have been on scripting helpers for under a month and have noticed that a lot of users asking questions have precreated functions for events like so:
function onTouch() print("I was touched") end script.Parent.Touched:Connect(function(onTouch)
Whereas I am more used to using nested functions like so:
script.Parent.Touched:Connect(function() print("I was touched") end)
These are just minor examples but they show what I mean. Could someone tell me which method is better or more efficient? I cannot tell much of a difference other than I prefer nested functions. Thanks!
Hello Phlegethon, good question. The last example you provided is not considered a nested function. Instead, it is simply just an unidentified function (more properly known as an anonymous function
) being passed as an argument to the Connect
method (methods are also functions). An anonymous function is just a function value that has not been assigned to a variable.
Nested functions are just that -- a function declared in the scope of another function. Here is one instance of a nested function
function foo() function bar() ... end end
To answer your question, it doesn't matter which version of your code you use if binding a function to a single event is all you are doing. Remember that a function is treated equally as a data type, just like all other data types inside of Lua. The difference between your two examples is analogous to the following circumstance...
local foo = x bar(x) -- vs bar(x)
...where x
could be replaced by your function value. Remember the convention of variables. If you are going to be using the same data more than once, you should (probably) create a variable for it. Otherwise, just let data be data.