Lua does not have a built-in system for object-oriented programming (OOP), creating classes, instantiating objects, et cetera. And so there are a lot of options for approaching object-oriented programming in Lua. Today I want to introduce you to what has become my favorite library for OOP in Lua: Middleclass by Enrique García, better known by his alias ‘kikito’ in the Lua and LÖVE communities.
A Short Introduction
The project page for Middleclass has a nice example. I want to supplement that with an example of my own. I could have used Middleclass when creating Luvent, like so:
local class = require("middleclass") local Luvent = class("Luvent")
Now instead of writing the function
Luvent.newEvent() I would automatically have a constructor:
Luvent:new(), and I could customize its behavior by defining
Luvent:initialize(). Middleclass would not require me to change the way I define all of the other methods, and so it easily fits into existing code-bases in my experience.
Middleclass allows you to define the usual metamethods with the exception of
__newindex. So if you are using those in existing code you will have to rework it, but again that has not posed a major problem in my experience. Some programmers use those metamethods to implement private data members. Middleclass has no explicit way to mark something as private; the convention is to use a leading underscore when naming private properties. To me that is good enough, but if you want privacy there are ways to do it.
Two other reasons I like Middleclass: easy static properties and mixins. The terse examples on the Middleclass wiki speak for themselves and demonstrate Middleclass’s nice API. The library lets you determine if an object
isSubclassOf(class), tests that are common in object-oriented languages. And so I believe many programmers who are used to OOP will feel comfortable with Middleclass.
Yes. I realize this article is short, but that is all I have to say about Middleclass. It is, in my opinion, the best library for OOP in Lua. Programmers who prefer the object-oriented paradigm should feel at home using Middleclass. And to top it all off it is easy to introduce into existing code-bases if you decide that an OOP approach would be beneficial.
So try it out. And even if you don’t use it I still suggest looking at the source code, as it’s an example of good Lua code and style.