Functions as Values

In Lua, a function is a value, just like a number or a string. You can store it in a variable, and you can pass it to another function as an argument.

Storing a function in a variable

function double(x)
    return x * 2
end

local twice = double
print(twice(5))

Output:

10

local twice = double has no parentheses, so it does not call double. It copies the function itself into twice. Now both names refer to the same function, and twice(5) runs it.

Passing a function as an argument

Because a function is a value, you can pass it to another function. Here applyTwice takes a function f and a number x. It calls f on x, and then calls f again on the result:

function applyTwice(f, x)
    return f(f(x))
end

print(applyTwice(double, 3))

Output:

12

double(3) is 6, and double(6) is 12. applyTwice does not know what f does. It only knows how to call it, so it works with any function that takes one number.

Pass the name without parentheses. With double(), Lua calls double right away with no argument, and x is nil:

function double(x)
    return x * 2
end

function applyTwice(f, x)
    return f(f(x))
end

print(applyTwice(double(), 3))

Output:

/usr/bin/lua5.4: main.lua:2: attempt to perform arithmetic on a nil value (local 'x')

Functions without a name

Sometimes you need a small function only once. Then you can write it right where you use it, with no name. This is an anonymous function:

function applyTwice(f, x)
    return f(f(x))
end

print(applyTwice(function(x) return x + 10 end, 1))

Output:

21

function(x) return x + 10 end creates a function that adds 10. It is passed straight to applyTwice, which adds 10 twice.

You can also store an anonymous function in a variable:

local square = function(x)
    return x * x
end

print(square(4))

Output:

16

In fact, function double(x) is a short way to write double = function(x). Both create a function value and store it in a name.

You will use anonymous functions again in the Tables section, when you sort a list with table.sort and tell it how to compare two items.

In the exercise, complete applyTwice and pass it an anonymous function that adds 3.