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.


29 – Managing Resources

In our implementation of arrays in the previous chapter, we did not need to worry about managing resources. They need only memory. Each userdatum representing an array has its own memory, which is managed by Lua. When an array becomes garbage (that is, inaccessible by the program), Lua eventually collects it and frees its memory.

Life is not always that easy. Sometimes, an object needs other resources besides raw memory, such as file descriptors, window handles, and the like. (Often these resources are just memory too, but managed by some other part of the system). In such cases, when the object becomes garbage and is collected, somehow those other resources must be released too. Several OO languages provide a specific mechanism (called finalizer or destructor) for that need. Lua provides finalizers in the form of the __gc metamethod. This metamethod only works for userdata values. When a userdatum is about to be collected and its metatable has a __gc field, Lua calls the value of this field (which should be a function), passing as an argument the userdatum itself. This function can then release any resource associated with that userdatum.

To illustrate the use of this metamethod and of the API as a whole, in this chapter we will develop two bindings from Lua to external facilities. The first example is another implementation for a function to traverse a directory. The second (and more substantial) example is a binding to Expat, an open source XML parser.