When to use a function inside a Function?

-- Hello!

-- This is what I'm talking about:

function Foo() -- function
   -- code
   local function Bar() -- second function
      -- also code
   end
   -- also also code
end

-- When will i ever do this in coding, and what are the benefits?

This is good for the “Don’t repeat yourself rule”

2 Likes

Isn’t that one of the Purposes for a ModuleScript?

1 Like

Using functions inside of functions is a very common, and very helpful method of keeping code organized. Both by splitting up code into smaller and easier to process bits.

Except defining a function inside of a function seems odd. Since the first function would limit the usefulness of the even having the second function, because of the local declaration being used.

local function Foo()
    --code
end

local function Bar()
    Foo()
    --code
end

Bar() --Calls Bar() and uses Foo(), but still allows Foo() to be called on it's own
1 Like

That’s why I’m asking When will i ever do this?

Never, because if you do it, you automatically become a psychopath.

1 Like

Guess I already am

1 Like

I would advise to never really do it, as it defeats the purpose of making the function as the code can’t really be “repeated”.

The only time I could ever see such a thing be needed is if you VERY BADLY don’t want Bar() to be used outside of the Foo() function. But again, you make functions to make reusable/modular code bases so why even use functions to begin with.

1 Like

I mean if you really wanted to, you could do this:

return SomeData, Bar()

local Data, func = Foo()
1 Like

You scare me.

It works, but I don’t like it :neutral_face:

It’s something you can do. But it goes off the norm so code readability in that way gets worse.

1 Like

Boo.

Sad

O K

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.