This is the documentation page for Module:Middleclass
| This module is rated as ready for general use. It has reached a mature form and is thought to be bug-free and ready for use wherever appropriate. It is ready to mention on help pages and other Wikipedia resources as an option for new users to learn. To reduce server load and bad output, it should be improved by sandbox testing rather than repeated trial-and-error editing. |
Middleclass is an object-oriented library for Lua, written by Enrique García Cota (kikito) and maintained at GitHub.
If you are familiar with Object Orientation in other languages (C++, Java, Ruby … ) then you will probably find this library easy to use.
For a quick look at how to use the library see below. For the full documentation, see the wiki page on GitHub.
Quick Example
local class = require('Module:Middleclass').class
Person = class('Person') --this is the same as class('Person', Object) or Object:subclass('Person')
function Person:initialize(name)
self.name = name
end
function Person:speak()
return 'Hi, I am ' .. self.name ..'.'
end
AgedPerson = class('AgedPerson', Person) -- or Person:subclass('AgedPerson')
AgedPerson.static.ADULT_AGE = 18 --this is a class variable
function AgedPerson:initialize(name, age)
Person.initialize(self, name) -- this calls the parent's constructor (Person.initialize) on self
self.age = age
end
function AgedPerson:speak()
local hi = Person.speak(self) -- "Hi, I am xx."
if self.age < AgedPerson.ADULT_AGE then -- accessing a class variable from an instance method
return hi .. '\nI am underaged.'
else
return hi .. '\nI am an adult.'
end
end
local p1 = AgedPerson:new('Billy the Kid', 13) -- this is equivalent to AgedPerson('Billy the Kid', 13) - the :new part is implicit
local p2 = AgedPerson:new('Luke Skywalker', 21)
mw.log(p1:speak())
mw.log(p2:speak())
Output:
Hi, I'm Billy the Kid. I am underaged. Hi, I'm Luke Skywalker. I am an adult.
Notes:
The standard way to do inheritance is class(‘A’, B). In addition to that, you can also do B:subclass(‘A’). Both expressions will return A (a subclass of B). A.super will return B.
When you call A:new(), only A:initialize() gets called – the constructor of B is not called by default. There is no super, instead you have to use an explicit self:
function A:initialize()
...
B.initialize(self, ...)
...
end
The same applies for non-constructor methods – there is no super keyword-like construction, so you must use explicit self calls.
