Lua - Anonymous Functions



An anonymous function as evident is a function which is not assigned any name. An anonymous function is often generated on the fly and assigned to a variable or passed as an argument to a function.

A anonymous function is mostly used to define a closure as it can capture the variables from the enclosing environment.

Syntax

variableName = function(parameter1, parameter2, ...)
  -- Function body
end

Example - Assigning Anonymous Function to a variable

Following example shows usage of anonymous functions.

main.lua

-- define an anonymous function and assign to a variable
adder = function(x, y)
  return x + y
end

-- call the function via variable
print(adder(2, 3))

Output

When the above code is built and executed, it produces the following result −

5

Example - Pass an Anonymous Function as an argument

Following example shows usage of anonymous functions.

main.lua

-- define a function which can accept a function
function applyOperation(a, b, func)
  return func(a, b)
end

-- call function while passing anonymous function 
result = applyOperation(5, 2, function(x, y) return x * y end)

-- print multiplication of two numbers as 10
print(result)

Output

When the above code is built and executed, it produces the following result −

10

Example - Anonymous Function as Closure

Anonymous functions are very useful in creating closures. When an anonumous function is defined and returned from an enclosing function, it forms a closure.

main.lua

function multiplyBy(factor)
   -- Anonymous function which closes over 'factor'
   return function(x) 
      return x * factor
   end
end

double = multiplyBy(2)
triple = multiplyBy(3)

-- Output: 10
print(double(5))

-- Output: 15
print(triple(5))

Output

When the above code is built and executed, it produces the following result −

10
15
Advertisements