Modules

Lua code can be located in multiple files and loaded as modules using the require function. Modules allow the user to group functionally related code in one file, and have other files import and use this functionality.

A module is loaded by passing in the name of the file without the .lua extension to the require function. A description of the require function can be found here: www.lua.org/pil/8.1.html.

The following example shows code from two files, mymodule.lua and use_mymodule.lua. These two script files can be packaged together and loaded onto the receiver using the steps in Loading and Running the Application.

-- File mymodule.lua

-- This is an example of creating a module called mymodule, which provides a single function, mymodule.example_func()

-- which can be used by other scripts that import this module.

 

-- Create an empty table, which acts as the container for the module.

local mymodule = {}

 

-- Create a function that is available for the module.

function mymodule.example_func()

  print("Hello from mymodule.example_func()")

end

 

return mymodule

 

-- File use_mymodule.lua

-- Import the functionality from the file mymodule.lua.

local mymodule = require("mymodule")

 

print("Hello from use_mymodule.lua")

mymodule.example_func()

 

Files can also be placed in subdirectories and loaded by specifying the path to the file in the require function. The path is specified as the directory name followed by a . and appending the filename of the module without the .lua extension. The following example shows a module located in a subdirectory called testdir being loaded using the require function.

-- File /testdir/mymodule.lua

 

-- This is an example of creating a module called mymodule2, which provides a single function, mymodule.example_func()

-- which can be used by other scripts that import this module.

 

local mymodule2 = {}

 

function mymodule2.example_func()

  print("Hello from mymodule2.example_func()")

end

 

return mymodule2

-- File use_mymodule2.lua

-- Import the functionality from the file mymodule2.lua. Note that the require function

-- needs the testdir path to import the file correctly.

 

local mymodule2 = require("testdir.mymodule2")

 

print("Hello from use_mymodule2.lua")

mymodule2.example_func()

 

Additional information on Lua modules can be found here: lua-users.org/wiki/ModulesTutorial.