A simple OOP library for Lua. It has inheritance, metamethods (operators), class variables and weak mixin support.
This fork adds a symlink to middleclass.lua
file in lua/
directory to allow
using middleclass
repo with Neovim plugin managers.
I have opened a pull request to
merge this into upstream. Also for convenience, this repo has a copy of upstream
wiki.
Since Neovim 0.5 most new plugins become written in Lua. Lua allows some sort of
OOP based on metatables, and most of the plugins which use OOP has a class.lua
file with practically identical code. To reduce the amount of boilerplate code,
I created this fork and suggest to use it as a standard class realization.
local class = require 'middleclass'
local Fruit = class('Fruit') -- 'Fruit' is the class' name
function Fruit:initialize(sweetness)
self.sweetness = sweetness
end
Fruit.static.sweetness_threshold = 5 -- class variable (also admits methods)
function Fruit:isSweet()
return self.sweetness > Fruit.sweetness_threshold
end
local Lemon = class('Lemon', Fruit) -- subclassing
function Lemon:initialize()
Fruit.initialize(self, 1) -- invoking the superclass' initializer
end
local lemon = Lemon:new()
print(lemon:isSweet()) -- false
See the github wiki page for examples & documentation.
You can read the CHANGELOG.md
file to see what has changed on each version of this library.
If you need help updating to a new middleclass version, read UPDATING.md
.
Just copy the middleclass.lua file wherever you want it (for example on a lib/ folder). Then write this in any Lua file where you want to use it:
local class = require 'middleclass'
This project uses busted for its specs. If you want to run the specs, you will have to install it first. Then just execute the following:
cd /folder/where/the/spec/folder/is
busted
Middleclass also comes with a small performance test suite. Just run the following command:
lua performance/run.lua
Middleclass is distributed under the MIT license.