Lua OOP classes usually end being:
- multi-file libraries, too difficult to understand
- very small libraries, not very powerful
Middleclass attemps to be a mid-sized library (~140 lines of code, on a single file), with clean, easy to understand code, and yet powerful enough to be used in most cases.
See the github wiki page for examples & documentation.
- ~140 lines of code
- top-level Object class
- all methods are virtual
- instance.class returns the instance’s class
Class.namereturns the class name (a string)
Class.superreturns its super class
- Class methods can be defined with Class.static.methodname
class(name)creates a subclass of
class(name, Superclass)creates a subclass of the class
SuperClass:subclass(name)also creates a subclass of the class
- Classes can define an
initializemethod for initializing new instances. They can accept an arbitrary number of params.
- Instances are created by doing
- SuperClass’ methods can be used by using this syntax:
- Classes can define an
- support for Lua metamethods: just define a method called
__add, etc. and your instances will be able to use it.
- A very simple mechanism for sharing functionality among a group of classes that are otherwise non-related.
- Mixins are just simple lua tables with functions inside them.
Class:include(mixin)will copy the function definitions of
mixincontains a function, called
included, that function will be invoked right after the functions have been copied. It allows for modifying the class more profoundly.
instanceis an instance of the class
Classis a subclass of
Class(or one of its superclasses) includes
Features left out:
- classes are not Objects (instances are)
- simulating a ‘super’ keyword (for performance concerns)
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:
package.path variable must be configured so that the folder in which middleclass.lua is copied is available, of course.
Please make sure that you read the license, too (for your convenience it’s now included at the beginning of the middleclass.lua file).
This project uses telescope for its specs. If you want to run the specs, you will have to install telescope first. Then just execute the following from the root inspect folder:
tsc -f spec/*
Middleclass also comes with a small performance test suit. Just run the following commant: