Lua Functions Anonymous functions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Creating anonymous functions

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

doThrice(function()
    print("Hello!")
end)

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
end

is actually just a shorthand for

double = function(x)
    return x * 2
end

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
end

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)
end

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



Got any Lua Question?