Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Should I be using nested or already created functions?

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!

3 comments

0

The top one is wrong, you don't even finish the parentheses. And it really doesn't matter at all.

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.

0

I wasnt trying to get it right. Just giving an example

1 answer

✓ Accepted answer

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.