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

Should I be using nested or already created functions?

Asked by 6 years ago

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!

0
The top one is wrong, you don't even finish the parentheses. And it really doesn't matter at all. theCJarmy7 1293 — 6y
0
I wouldn't say it doesn't matter -- if there is a circumstance where you wish to reuse the code inside the body of function f, then creating a variable for it is certainly necessary. UnitVector 47 — 6y
0
I wasnt trying to get it right. Just giving an example User#21908 42 — 6y

1 answer

Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

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.

Ad

Answer this question