Chapter 4. Making Your API Classy
Often, the functions in an API can be broken down into a few categories. Suppose, for instance, that a library allows you to manage both image files and movie files. In cases like this, it’s natural to use a class to represent each conceptual object or task being performed by a subset of the interface—for example, we could have an Image class and a Movie class. This chapter covers common methods of defining classes in Lua; implementing inheritance; and defining custom, class-like userdata types in C.
EatyGuy Version 6: Writing a Class in Lua
Most of Lua’s design is simple and transparent, including the building blocks of Lua’s class system. Nonetheless, Lua does ask for some depth of thought when it’s time to implement classes and class inheritance. This is due to the fact that classes in Lua are not directly supported by the language; rather, they are enabled by giving coders the low-level pieces needed to be assembled into class mechanics. Because of this, I’ll cover Lua classes in more detail than I’ve previously covered other language features.
In this chapter, we add enemies to EatyGuy. Let’s call them baddies because it sounds more fun. This is a great opportunity to implement a class–subclass relationship: the player and baddies can share a common superclass that we’ll call Character, whereas the baddy-specific behavior will live in subclass called Baddy. As is common in some languages, we’ll capitalize the names of classes and class-like ...