Lua modules and packages


Release date:2023-10-08 Update date:2023-10-13 Editor:admin View counts:246

Label:

Lua modules and packages

Module is similar to a wrapper library. Starting from Lua 5.1, Lua adds a standard module management mechanism that allows you to put some common code in a file to API the form of the interface is called elsewhere, which is conducive to code reuse and reduce code coupling.

Lua the module is composed of known elements such as variables, functions, etc. table so it is simple to create a module, which is to create a table and then put the constants and functions that need to beexported into it, and finally return this table just do it. The following is the creation of a custom module module.lua the format of the file code is 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

From the above, we can see that the structure of the module is a table so it can be called like an operation table to manipulate constants or functions in the calling module that way.

Above. func2 the local variable declared as a block represents a private function, so the private function in the module cannot be accessed from the outside and must be called through the public function in the module.

Require function

Lua provides a file named require is used to load the module to load a module, simply call it. For example:

require("<module name>")

Or

require "<module name>"

Execution require which is made up of module constants or functions table and also defines a file that contains the table the global variable.

Test_module.lua file

-- test_module.lua file
-- The module module is the module. lua mentioned earlier
require("module")

print(module.constant)

module.func3()

The result of the above code execution is:

This is a constant
This is a private function!

Or define an alias variable for the loaded module to make it easy to call:

Test_module2.lua file

-- test_module2.lua file
-- The module module is the module. lua mentioned earlier
-- Alias variable m
local m = require("module")

print(m.constant)

m.func3()

The result of the above code execution is:

This is a constant
This is a private function!

Loading mechanism

For custom modules, module files can not be placed in any file directory, function require it has its own file path loading strategy, which attempts to load from the Lua load the module in the file or C library.

require for search Lua the path to the file is stored in the globalvariable package.path in, when Lua after startup, the environmentvariable LUA_PATH to initialize the environment variable if the environment variable is not found, it is initialized with a default path defined at compile time.

Of course, if not, LUA_PATH this environment variable can also be customized and opened in the current user root directory .profile file (if not, create, open .bashrc files are also available), for example, adding “~ / lua/” path LUA_PATH in the environment variable:

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

The file paths are separated by a “;” sign, and the last two “;;” means that the newly added path is followed by the original default path.

Next, update the environment variable parameters to take effect immediately.

source ~/.profile

At this point, assume that the value of package.path:

/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 call require("module") will try to open the following file directory 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, the call is called package.loadfile to load the module. Otherwise, you will go to the C library.

The file path of the search is from the global variable package.cpath and this variable is obtained through the environment variable LUA_CPATH in the beginning.

The search strategy is the same as above, except that now the search strategy is so or dll a file of type. If you can find it, then require it will pass. package.loadlib to load it.

C packet

Lua is easy to combine with C, using C for Lua write a bag.

Unlike Lua , and the easiest way to implement it in most systems is through the dynamic link library mechanism.

Lua in a place called loadlib all the functions of dynamic connections are provided in the This function takes two parameters: the absolute path to the library and the initialization function. So a typical example of a call is as follows:

local path = "/usr/local/lua/lib/libluasocket.so"
local f = loadlib(path, "luaopen_socket")

loadlib function loads the specified library and connects to the Lua . However, it does not open the library (that is, it does not call theinitialization function), instead it returns the initialization function as``Lua`` , so that we can go directly to the Lua call him in.

If there is an error loading the dynamic library or finding the initialization function loadlib will return nil and error messages. We can modify the previous code to detect errors and then call theinitialization 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()  -- Truly open the library

In general, we expect a binary publishing library to contain a similar to the previous code snippet stub file, you can put it in a directory whenyou install the binary library, and you only need to modify it stub the file corresponds to the actual path of the binary library.

Set stub directory where the file is located is added to the LUA_PATH so that after it is set, you can use the require the function loads the C library.

Powered by TorCMS (https://github.com/bukun/TorCMS).