You can edit almost every page by Creating an account and confirming your email.

Module:Middleclass/doc

From EverybodyWiki Bios & Wiki
Revision as of 04:13, 29 March 2018 by WikiMaster (talk | contribs) (1 revision imported)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

This is the documentation page for Module:Middleclass

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.


This module "Middleclass/doc" is from Wikipedia if otherwise notified