Lua - Submodule



When a module becomes very large, it is better to organize it into either small modules or we can create submodules. Lua supports submodule with an advantage that variable of main module is accessible in a submodule.

A submodule can be created by creating a nested table. Main module is represented by a table and submodules are represented by nested tables.

Creating a Module with SubModules

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

utility.lua

-- main module
local utils = {}

-- submodule
utils.stringutils = {}

-- function of submodule
function utils.stringutils.capitalize(s)
   -- call main module function
   logEntry(s)
   return string.upper(s:sub(1,1)) .. s:sub(2)
end

-- Submodule 'config'
utils.config = {
   version = "1.0",
   author = "Tutorialspoint",
   settings = {
      timeout = 30,
      retries = 3 
   }
}

-- function of main module accessing submodule's function
function utils.greetUser(user)
   print("Greetings, " .. utils.stringutils.capitalize(user) .. "!")
end

-- function of main module
function logEntry(entry)
   print("Utility Function called with input: " .. entry)
end

return utils

Now, in order to access submodules and modules in another file, say, moduletutorial.lua, you need to use the following code segment.

moduletutorial.lua

-- load the module
utils = require("utility")

-- call the utils function
utils.greetUser("Robert")

-- call the submodule function
print(utils.stringutils.capitalize("julie"))

-- access the submodule entries
print(utils.config.version)

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−

Utility Function called with input: Robert
Greetings, Robert!
Utility Function called with input: julie
Julie
1.0

Explanation

utility.lua

  • We've created an empty table utils as a module and a nested table stringutils as a submodule.

  • Using dot(.) notation, we're created nested module funcion as capitalize() in stringutils module.

  • utils.config is another submodule with properties only.

  • utils.greetUser() is main module function and is calling submodule function capitalize()

  • capitalize(s) of submodule is calling main module function logEntry().

  • In the end, we're returning the utility table as a module.

moduletutorial.lua

  • utils = require("utility") statement is used to load the main module and assign to utils variable.

  • As next, we're accessing utility module's function using dot(.) notation and corresponding result is printed.

  • We're accessing submodules methods and properties using dot notation.

Advertisements