YouTip LogoYouTip

Lua Modules Packages

Modules are similar to encapsulated libraries. Starting from Lua 5.1, Lua has included a standard module management mechanism. It allows common code to be placed in a single file and called from other places via an API interface, which promotes code reuse and reduces 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 that need to be exported into it, and finally return this table. Below is the code format for creating a custom module named `module.lua`: ```lua -- Filesnamed 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!") end local function func2() print("This is a private function!") end function module.func3() func2() end return module As shown above, the structure of a module is essentially a table structure. Therefore, you can operate on or call the constants or functions within a module just like you would with elements in a table. The `func2` declared above is a local variable of the block, meaning it is a private function. Therefore, this private function cannot be accessed from outside the module; it must be called through a public function within the module. * * * ## The require Function Lua provides a function named `require` for loading modules. To load a module, you simply need to call it. For example: ```lua require("") or ```lua require "" After executing `require`, it returns a table composed of the module's constants or functions and also defines a global variable containing that table. ## test_module.lua File ```lua -- test_module.lua Files -- module The module is the module mentioned above..lua require("module") print(module.constant) module.func3() The result of executing the above code is: This is a constant.This is a private function! Alternatively, you can define an alias variable for the loaded module to make it easier to call: ## test_module2.lua File ```lua -- test_module2.lua Files -- module The module is the module mentioned above..lua -- Alias variable m. local m =require("module") print(m.constant) m.func3() The result of executing the above code is: This is a constant.This is a private function! ### Loading Mechanism For custom modules, the module file cannot be placed just anywhere. The `require` function has its own file path loading strategy. It will attempt to load modules from Lua files or C libraries. The path used by `require` 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 `LUA_PATH` environment variable. If that environment variable is not found, it uses a default path defined at compile time for initialization. Of course, if there is no `LUA_PATH` environment variable, you can customize it. Open the `.profile` file in the current user's home directory (create it if it doesn't exist; opening `.bashrc` also works). For example, to add the path `~/lua/` to the `LUA_PATH` environment variable: ```bash #LUA_PATHexport LUA_PATH="~/lua/?.lua;;" File paths are separated by semicolons (`;`). The final two semicolons (`;;`) indicate that the original default path should be appended after the newly added path. Then, update the environment variable parameters to make them take effect immediately. ```bash source ~/.profile At this point, assuming 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 attempt to open the following 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, it will call `package.loadfile` to load the module. Otherwise, it will look for a C library. The search path for files is obtained from the global variable `package.cpath`, which is initialized via the `LUA_CPATH` environment variable. The search strategy is the same as above, except now it searches for files of type `.so` or `.dll`. If found, `require` will load it via `package.loadlib`. * * * ## C Packages Lua and C are easy to combine, using C to write packages for Lua. Unlike writing packages in Lua, C packages must be loaded and linked before use. On most systems, the easiest way to implement this is through the dynamic linking library mechanism. Lua provides all dynamic linking functionality within a function called `loadlib`. This function takes two parameters: the absolute path of the library and the initialization function. So a typical call looks like this: ```lua 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 (i.e., it does not call the initialization function). Instead, it returns the initialization function as a Lua function, which we can then call directly in Lua. If there is an error loading the dynamic library or finding the initialization function, `loadlib` will return `nil` and an error message. We can modify the previous code segment to detect errors and then call the initialization function: ```lua local path ="/usr/local/lua/lib/libluasocket.so" -- or path. = "C:windowsluasocket.dll",This is on the Windows platform. local f =assert(loadlib(path,"luaopen_socket")) f()-- Actually open the library. Generally, we expect binary distribution libraries to include a stub file similar to the code segment above. When installing a binary library, you can place it in any directory; you just need to modify the actual path to the binary library in the corresponding stub file. Add the directory containing the stub file to `LUA_PATH`. Once configured this way, you can use the `require` function to load C libraries.
← Cpp Web ProgrammingLua Object Oriented β†’