This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.


15.3 – Packages and Files

Typically, when we write a package, we put all its code in a single file. Then, to open or import a package (that is, to make it available) we just execute that file. For instance, if we have a file complex.lua with the definition of our complex package, the command require "complex" will open the package. Remember that require avoids loading the same package multiple times.

A recurring issue is the relationship between the file name and the package name. Of course, it is a good idea to relate them, because require works with files, not with packages. One solution is to name the file after the package, followed by some known extension. Lua does not fix any extension; it is up to your path to do that. For instance, if your path includes a component like "/usr/local/lualibs/?.lua", than the package complex may live in a complex.lua file.

Some people prefer the reverse, to name the package after the file name, dynamically. That is, if you rename the file, the package is renamed, too. This solution gives you more flexibility. For instance, if you get two different packages with the same name, you do not have to change any of them, just rename one file. To implement this naming scheme in Lua, we use the _REQUIREDNAME variable. Remember that, when require loads a file, it defines that variable with the virtual file name. So, you can write something like the following in your package:

    local P = {}   -- package
    if _REQUIREDNAME == nil then
      complex = P
    else
      _G[_REQUIREDNAME] = P
    end
The test allows us to use the package without require. If _REQUIREDNAME is not defined, we use a fixed name for the package (complex, in the example). Otherwise, the package registers itself with the virtual file name, whatever it is. If a user puts the library in file cpx.lua and runs require"cpx", the package loads itself in table cpx. If another user moves the library to file cpx_v1.lua and runs require"cpx_v1", the package loads itself in table cpx_v1.