Lua - Returning functions from Modules



Lua modules allows to return functions. This capability of Lua allows us to encapsulate certain data and functionality in a module and then expose only functions which are required.

When we create a module, we return a table. This table can contain data as well as functions. These functions are part of module. Now we can create a factory function which can return a function.

Syntax

Let's define a module file mymath.lua as described below −

mymath.lua

-- define a module
local mymath =  {}

-- create a factory function
function mymath.getMultiplier(factor)
   return function(n)
      return n * factor
   end
end

return mymath	

Now, in order to access factory function from Lua module in another file, say, moduletutorial.lua, you need to use the following code segment.

moduletutorial.lua

-- load the module
mymathmodule = require("mymath")

-- get multiplier function
local doubler = mymathmodule.getMultiplier(2)
local tripler = mymathmodule.getMultiplier(3)

-- prints Double of 5: 10
print("Double of 5: ", doubler(5))

-- prints Triple of 5: 15 
print("Triple of 5: ", tripler(5))

Output

In order to run this code, we need to place the two Lua files in the same directory or alternatively, you can place the module file in the package path and it needs additional setup. When we run the above program, we will get the following output−

Double of 5:    10
Triple of 5:    15

Explanation

  • We're created a module named mymath and defined a factory function getMultiplier(factor) within it.

  • getMultiplier() function returns an anonymous function as a closure. This function accepts a parameter n and multiplies it with the enclosing function's parameter factor. The inner function being a closure remembers the value of factor passed at the time of creation.

  • In mymathtutorial.lua, we've imported mymath module using require. Now using mymath.getMultiplier(2), module returns the anonymous function with factor as 2. The returned function is assigned to variable doubler and similarly getMultiplier(3) is assigned to tripler.

  • Now we are calling the functions as doubler(5) and tripler(5) are printing the result.

Advantages of Returning functions from a Module

  • Function Factories − A factory function is a function which return a function to create specialized functionality as per given parameter(s).

  • Encapsulation and State − We can implement encapsulation using functions within a module. A module can contain data which is accessible only though functions of modules.

  • Customized functions − A factory function can return customized functions based on parameters provided.

  • Higher-Order Functions − A higher order function is a function which can be assigned to a variable or passed as a parameter to a function. A factory function allows creating such high order functions.

Advertisements