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


15 – Packages

Many languages provide mechanisms to organize their space of global names, such as modules in Modula, packages in Java and Perl, or namespaces in C++. Each of these mechanisms has different rules regarding the use of elements declared inside a package, visibility, and other details. Nevertheless, all of them provide a basic mechanism to avoid collision among names defined in different libraries. Each library creates its own namespace and names defined inside this namespace do not interfere with names in other namespaces.

Lua does not provide any explicit mechanism for packages. However, we can implement them easily with the basic mechanisms that the language provides. The main idea is to represent each package by a table, as the basic libraries do.

An obvious benefit of using tables to implement packages is that we can manipulate packages like any other table and use the whole power of Lua to create extra facilities. In most languages, packages are not first-class values (that is, they cannot be stored in variables, passed as arguments to functions, etc.), so these languages need special mechanisms for each extra trick you may do with a package.

In Lua, although we always represent packages as tables, there are several different methods to write a package. In this chapter, we cover some of these methods.