5.6 Anonymous Functions

In the previous few examples we wrote “one time use” functions that were defined and then immediately invoked or returned.

Someone who came before us also had to do this. And they had to do it one too many times and got tired of having to constantly come up names for these one-time in one-place functions.

So they created a way to define functions inline that can be immediately invoked or returned or passed into another function.

And that is the story of how the anonymous function was born. Maybe.

An anonymous function is a function that does not require a name assignment. Hence the name?

Because anonymous functions don’t require a variable name, only the function keyword the parenthesis notation is required to define the function.

Lua
local function getSomeFunction(argument)
	if argument == 1 then
		return function()
			print("Hello function 1!")
		end

	else
		return function()
			print("The meaning of life is 3.14159!")
		end
	end
end

local someFn = getSomeFunction(42)
someFn()

Not only can anonymous functions be defined in place, they can also be invoked in place. This allows us to something outrageous looking like this:

Lua
(function(argument)
	print("Run anonymous function!", argument)
end)("3.14159")

The first set of parenthesis contains the function definition and then the second set are the notation to invoke the function, which we also pass an argument.

Perhaps a more useful scenario is for creating a closure to contain local data only it can access.

Lua
local someFn = (function(argument)
	local x = argument
	
	return function(arg)
		print(x * arg)
	end
end)("3.14159")

someFn(2) --6.28318
someFn(4) --12.56636
someFn(8) --25.13272

Initially we set the value for x. After the outer function returns, x becomes “private” and now accessible only to the inner function.


Earlier I said that functions should be abstracted out so they can be reused. And anonymous functions seem to contradict this since they are “single use” and clutter up the space in some statement.

And you’d be correct.

Anonymous functions are what are known in computer science as syntactic sugar. Meaning they don’t generally introduce some important functionality of their own but when used in place of some other syntax can make code easier to read or express.

Similar to the single line conditional statements we’ve also been using (i.e. ‘foo and bar or baz‘), when an anonymous function is able to make some bit of code more concise, it helps us write more maintainable code.

As developer, you will make the decision on when one or the other works best.

In the context of Roblox game development, perhaps one of the most common use cases for anonymous functions are…