Lua Modules

How to define a module in Lua?

A module in Lua is a way to organize code into reusable units. Modules are defined using the module keyword. The basic syntax for defining a module is as follows:

Lua
module(name, [parent])
Use code with caution. Learn more
name is the name of the module.
parent is the name of the parent module, or nil if there is no parent module.
The module keyword creates a new table and assigns it to the global variable with the given name. This table is the namespace for the module.

The following is an example of a module that defines a function called factorial():

Lua
module(“factorial”)

function factorial(n)
if n == 0 then
return 1
else
return n * factorial(n - 1)
end
end
Use code with caution. Learn more
This module can be used in other Lua scripts by using the require function. The require function loads a module and returns the module table.

The following is an example of how to use the factorial module:

Lua
require(“factorial”)

print(factorial(5))
Use code with caution. Learn more
This code will print the factorial of 5, which is 120.

Here are some additional things to keep in mind when defining a module in Lua:

The module keyword can only be used at the top of a file.
The name argument must be a valid Lua identifier.
The parent argument can be any valid Lua identifier, including nil.
The module table can contain any valid Lua data, such as functions, variables, and tables.
The module table can be accessed by using the require function.

How to use a module in Lua?

o use a module in Lua, you need to use the require function. The require function loads a module and returns the module table.

The basic syntax for using the require function is as follows:

Lua
require(name)
Use code with caution. Learn more
name is the name of the module.
The require function will search for the module in the following locations:

The current directory.
The directories in the package.path table.
The directories in the package.cpath table.
If the module is not found, the require function will raise an error.

Once the module is loaded, you can access its functions and variables by using the dot notation. For example, if the module is named factorial, you can access the factorial() function by using the following code:

Lua
require(“factorial”)

print(factorial(5))
Use code with caution. Learn more
This code will print the factorial of 5, which is 120.

Here are some additional things to keep in mind when using a module in Lua:

The require function can only be used in the global scope.
The name argument must be a valid Lua identifier.
The module table can be accessed by using the dot notation.
The module table can be modified, but this is not recommended.
I hope this helps! Let me know if you have any other questions.

References: Lua - Modules
Lua Modules - Create - Use - Best Practices

4 Likes