Lua Anonymous functions


Creating anonymous functions

Anonymous functions are just like regular Lua functions, except they do not have a name.


As you can see, the function is not assigned to any name like print or add. To create an anonymous function, all you have to do is omit the name. These functions can also take arguments.

Understanding the syntactic sugar

It is important to understand that the following code

function double(x)
    return x * 2

is actually just a shorthand for

double = function(x)
    return x * 2

However, the above function is not anonymous as the function is directly assigned to a variable!

Functions are first class values

This means that a function is a value with the same rights as conventional values like numbers and strings. Functions can be stored in variables, in tables, can be passed as arguments, and can be returned by other functions.

To demonstrate this, we'll also create a "half" function:

half = function(x)
    return x / 2

So, now we have two variables, half and double, both containing a function as a value. What if we wanted to create a function that would feed the number 4 into two given functions, and compute the sum of both results?

We'll want to call this function like sumOfTwoFunctions(double, half, 4). This will feed the double function, the half function, and the integer 4 into our own function.

function sumOfTwoFunctions(firstFunction, secondFunction, input)
    return firstFunction(input) + secondFunction(input)

The above sumOfTwoFunctions function shows how functions can be passed around within arguments, and accessed by another name.