This question is just out of pure curiosity, but can a function be inside of a function?
Can you have a function inside of a function?
2 answers
Yes. Actually, functions are values so you can put a function anywhere you can put, say, a string.
What do I mean by "functions are values"?
I can give you a function and you can then invoke that function. For example, function(x) return x * 2 end is an anonymous function literal (a nameless function value) that doubles a number.
You can use these anywhere you want. A function definition is just sugar for an assignment to an anonymous function; the following two are the same:
function blah()
end
blah = function()
end
So you can of course define functions inside functions:
function outside()
function inside()
end
end
print( inside ) -- nil
outside()
print( inside ) -- function 0x123456
-- it's a global! careful!
A warning about this: inside is a global variable. You rarely want to use global variables when you're coding. If you have a good reason for inside to be hidden in the guts of outside, then it should almost definitely be defined as local:
function outside()
local function inside()
end
end
outside()
print(inside) -- nil
Closures
There is a concept called a closure which is a function that has some context to it.
This is a common case where you define a function inside of a function.
For example, imagine we want to make numbers bigger. We could have something like the double function I wrote before, in addition to triple, etc:
double = function(x) return x * 2 end
triple = function(x) return x * 3 end
tenfold = function(x) return x * 10 end
But it can be annoying to keep writing the same thing over and over for just a slightly different number. It could be really bad if these were each doing something much more complicated and were dozens of lines long.
So we want to make a way to build these functions. Maybe something like:
function Scaler(n)
return function(x) return x * n end
end
This is a closure over n, since it remembers the n value that was passed in.
Thus we can define
double = Scaler(2)
triple = Scaler(3)
tenfold = Scaler(10)
half = Scaler(1/2)
quarter = Scaler(1/4)
etc. This is a very practical reason to define functions inside functions.
2 comments
So those are what closures are... Neat.
Thanks for the in depth description!
Yes you can, but you must fire the first one for the second one to fire aswell.
function Touchdown()
function Interception()
print'Troy Aikmen just said Int!'
end
end
Touchdown()
Interception()
OR easier way,
function Touchdown()
print'Touchdown in the end-zone'
end
function Interception()
Touchdown()
end
Interception()
1 comment
There's not a good reason to define a global function inside another function
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
Yes.