Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Lua Modules and Packages

Lua Modules and Packages

A module is similar to an encapsulated library. Starting from Lua 5.1, Lua added a standard module management mechanism. You can put some common code in a file and call it elsewhere in the form of an API interface, which is beneficial for code reuse and reducing code coupling.

A Lua module is a table composed of known elements such as variables and functions. Therefore, creating a module is simple: create a table, put the constants and functions to be exported into it, and finally return this table. The following creates a custom module module.lua, with the file code format as follows:

-- the file name is module.lua

-- define a module named module

module

=

{

}

 

-- define a constant

module

.

constant

=

"this is a constant"

 

-- define a function

function

module

.

func1

(

)

   

io.write

(

"this is a public function!\n"

)

end

 

local

function

func2

(

)

   

print

(

"this is a private function!"

)

end

 

function

module

.

func3

(

)

    func2

(

)

end

 

return

module

As can be seen above, the structure of a module is the structure of a table, so you can operate on and call constants or functions in the module just as you would operate on and call elements in a table.

The func2 above is declared as a local variable of the block, meaning it is a private function. Therefore, this private function in the module cannot be accessed from outside and must be called through a public function in the module.


The require function

Lua provides a function named require to load modules. To load a module, you only need to call it simply. For example:


require("<模块名>")

or


require "<模块名>"

After executing require, a table composed of the module's constants or functions is returned, and a global variable containing that table is also defined.

The test_module.lua file

-- the test_module.lua file

-- the module module is the module.lua mentioned above

require

(

"module"

)

 

print

(

module

.

constant

)

 

module

.

func3

(

)

The execution result of the code above is:


这是一个常量
这是一个私有函数!

Alternatively, define an alias variable for the loaded module for easy calling:

The test_module2.lua file

-- the test_module2.lua file

-- the module module is the module.lua mentioned above

-- alias variable m

local

m

=

require

(

"module"

)

 

print

(

m

.

constant

)

 

m

.

func3

(

)

The execution result of the code above is:


这是一个常量
这是一个私有函数!

Loading mechanism

For custom modules, the module file cannot be placed in just any directory. The require function has its own file path loading strategy, which tries to load the module from a Lua file or a C library.

The path that require uses to search for Lua files is stored in the global variable package.path. When Lua starts, it initializes this environment variable with the value of the environment variable LUA_PATH. If the environment variable is not found, it is initialized with a default path defined at compile time.

Of course, if there is no LUA_PATH environment variable, you can also set it yourself. Open the .profile file in the current user's root directory (create it if it doesn't exist; you can also open the .bashrc file), for example, to add the "~/lua/" path to the LUA_PATH environment variable:


#LUA_PATH
export LUA_PATH="~/lua/?.lua;;"

File paths are separated by ";". The last two ";;" indicate that the original default path is appended after the newly added path.

Then update the environment variable parameters to make them take effect immediately.


source ~/.profile

Suppose at this point the value of package.path is:


/Users/dengjoe/lua/?.lua;./?.lua;/usr/local/share/lua/5.1/?.lua;/usr/local/share/lua/5.1/?/init.lua;/usr/local/lib/lua/5.1/?.lua;/usr/local/lib/lua/5.1/?/init.lua

Then when calling require("module"), it will try to open the following file directories to search for the target.


/Users/dengjoe/lua/module.lua;
./module.lua
/usr/local/share/lua/5.1/module.lua
/usr/local/share/lua/5.1/module/init.lua
/usr/local/lib/lua/5.1/module.lua
/usr/local/lib/lua/5.1/module/init.lua

If the target file is found, package.loadfile will be called to load the module. Otherwise, it will look for a C library.

The searched file path is obtained from the global variable package.cpath, which is initialized through the environment variable LUA_CPATH.

The search strategy is the same as above, except that now it searches for files of type so or dll. If found, require will load it through package.loadlib.


C packages

Lua and C are easy to combine. Use C to write packages for Lua.

Unlike writing packages in Lua, a C package must first be loaded and linked before use. In most systems, the easiest way to achieve this is through a dynamic link library mechanism.

Lua provides all dynamic linking functionality in a function called loadlib. This function has two arguments: the absolute path of the library and the initialization function. So a typical call example is as follows:

local

path

=

"/usr/local/lua/lib/libluasocket.so"

local

f

=

loadlib

(

path

,

"luaopen_socket"

)

The loadlib function loads the specified library and links it to Lua, but it does not open the library (that is, it does not call the initialization function). Instead, it returns the initialization function as a Lua function, so that we can call it directly in Lua.

If an error occurs when loading the dynamic library or finding the initialization function, loadlib will return nil and an error message. We can modify the previous code to detect the error and then call the initialization function:

local

path

=

"/usr/local/lua/lib/libluasocket.so"

-- or path = "C:\windows\luasocket.dll", this is under the Window platform

local

f

=

assert

(

loadlib

(

path

,

"luaopen_socket"

)

)

f

(

)

 

-- actually open the library

In general, we expect a binary release library to contain a stub file similar to the previous code snippet. When installing the binary library, you can place it in any directory; you only need to modify the actual path of the binary library in the stub file.

Add the directory where the stub file is located to LUA_PATH. Once set up this way, you can use the require function to load the C library.