Module:Middleclass/doc

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 very easy to use.

The code is reasonably commented, so you might want to employ some time in reading through it, in order to gain insight of Lua’s amazing flexibility.

Quick Example
Output:

Hi, I'm Billy the Kid. I am underaged. Hi, I'm Luke Skywalker. I am an adult.

Comparing classes and objects
You can compare classes and objects with the built-in methods,  , and.

Caution: this code will throw an error if obj is not an object, or if aClass is not a class (since they will not implement isInstanceOf, isSubclassOf or includes). If you are unsure of whether obj and aClass are an object or a class, you can use the methods in Object. This is a special object that can be obtained from the class object.

It is possible to get a special object Object from the class function.

The methods in Object are prepared to work with random types, not just classes and instances:

Metamethods
Metamethods can do funky stuff like allowing additions in our instances.

Let’s make an example with

Output:

Point: [100, 200] Point: [35, -10]

The complete list of supported methods can be seen on middleclass’ source code:

You may notice that  is missing. That metamethod is reserved for the lib and can’t be used. On middleclass 1.x there was a way around this (via a mixin) but for now I don’t recommend using this metamethod with classes. You will probably be better off using a pure Lua table instead, if you need that.

Note about Lua 5.2: This new version of Lua adds support for 3 new metamethods,   &. These methods are now also included in middleclass. But you will need to be running Lua 5.2 (or Luajit compiled with the  flag) in order to be able to use them.

Mixins
Mixins can be used for sharing methods between classes, without requiring them to inherit from the same father.

Output:

flap flap flap I am a Bee flap flap flap I am a Bat

Included
Mixins can provide a special function called 'included'. This function will be invoked when the mixin is included on a class, allowing the programmer to do actions. The only two parameters are the mixin (normally implicit) and the class.

Output:

EnglishMan drinks coffee at 5 Spaniard drinks coffee at 6 tom: Mmm I love coffee at 5 juan: It is not the time to drink coffee! juan: Mmm I love coffee at 6

Naming Conventions
What follows is a set of recommendations used for naming objects with MiddleClass. These are completely optional, but will be used in all the modules directly dependent on MiddleClass (such as middleclass-extras or PÄSSION)

Classes and packages

 * Package names should be lowercased and separated by underscores: package_name
 * Class names & mixin names should begin with Uppercase, and use camelCase notation: MyClass, MyMixin
 * One exception to this rule is when classes are declared inside packages in that case, they can be declared as follows:


 * Another exception is for internal classes (classed declared inside classes)

Attributes, instances and constants

 * Attributes begin with lowercase, and use camelCase: MyClass.attributeOne, MyClass.attributeTwo
 * An underscore can precede the initial lowercase if the attribute is supposed to be private: MyClass._privateAttribute
 * Variables pointing to instances of classes should start with lowercase and be camelCased: myInstance = MyClass:new
 * Constants should be ALL_UPPERCASED, and use underscores for word separations: MyClass.MY_CONSTANT
 * Private attributes should be preceded with an underscore: _myPrivateAttribute

Methods

 * Methods should begin with lowercase, and use camelCase: MyClass.myMethod
 * When possible, methods should use explicit verbs: getX instead of x
 * Instance methods should be declared using the colons, so they have an implicit ‘self’ parameter:


 * Class methods should use the special property ‘static’ for being defined:


 * Private methods should be preceded with an underscore:

File names

 * In general, filenames will be named using semicolons and lowercase letters: my-file-name.lua
 * Folders containing a package should be called the same way as the package itself: my_package should be stored under a folder called /my-package/
 * If a file only defines a class, it should be named like the class, including lowercase/uppercase: a class named MyClass should be defined on a file named MyClass.lua
 * Same happens with Mixins: the file defining MyMixin should be called MyMixin.lua
 * If a class is so big it needs to be split on several files, precede all the files defining this class with the class name, followed by an underscore and an explanation of what the file defines:

Game.lua Game_MainMenu.lua Game_OptionsMenu.lua Game_Play.lua

Private members
There are several ways you can make private parameters with middleclass.

Underscoring
The simplest one is just to precede your attributes with underscores. This is actually written on the Lua 5.1 reference, section 2.1, “Lexical conversions”, as a way to say “this is here, but please don’t use it”.

However, this isn’t really making the properties “hidden”. Private class attributes

Private class attributes
In general, the way of “really” getting hidden functions or variables consists on using Lua’s scoping rules. The simplest way of using this is creating each of your classes on separate files, and then declaring any private variable or functions as local, on the “root” scope of the file.

Example:

The scope of local declarations on a lua file is the file itself. If you declare something “local” in one file it is not available on others, even if they “require” that file.

Let me explain what happens here. The _internalClassCounter = 4 line is, in reality, creating a new global variable called internalClassCounter, and assigning it 4. The “really internal” one is “out of reach” on main.lua (unless someone does really tricky stuff with the environments). So getCount works as expected. Private instance methods

Private instance methods
It is also possible to declare private methods. The trick here is not to “include” them on the class definition. On the following example, we will not declare it on ; instead we’ll create a local function. Since we’re not using the : operator any more, we have to make the “self” parameter explicit. Also, since we have to make it local, we have to deviate from the “usual” way of declaring Lua functions (the “usual” way of declaring functions makes them global):

This technique also allows the creation of private class methods. In MiddleClass, there’s really no difference between class methods and instance methods; the difference comes from what you pass to their ‘self’ parameter. So if you invoke _secretMethod like this: _secretMethod(MyClass3) it will be a class method.

A slightly more efficient way of creating a class method would be getting rid of the ‘self’ parameter and use MyClass3 directly on the method’s body:

This gives a bit more of flexibility when overriding public class methods on subclasses.

Finally, a subtle point regarding recursive private methods. If you need to create a private method that calls himself, you will need to declare the variable first, and then (on the next line) initialize it with the function value. Otherwise the variable will not be available when the function is created

Output:

Recursion level 5 Recursion level 4 Recursion level 3 Recursion level 2 Recursion level 1 Last recursion

Private Instance attributes
Instance attributes are a little bit trickier to implement, since we only have one scope to “hide stuff in”, and it has to cope with multiple instances.

One way to do this is using one private class variable as a ‘stash’. If you use one table instead of just a number, you can and hide there all the private information you may need. One problem with this approach is that you need to come out with a ‘key’ per ‘instance’.

Fortunately this is a very simple thing to do, since in lua you can use nearly any type of object as a key – So you can use the instances themselves as keys. In other words, we use ‘self’ as a key.

One problem with this approach is that instances might not be liberated by the garbage collector once they are not used any more (since there’s a reference to them on the ‘stash’ keys). In order to avoid this, we can make the ‘stash’ a weak table.

On the following example, the name attribute is public, but age and gender are private.

Our ‘secret stash’ in the following example will be called _private.

-By the way, the following example also shows how you can do “read-only-ish attributes”: you make them private, and make getters for them, but not setters.

Private members on the same file
There’s also a way of creating private members that other classes/methods on the same file can’t access, if you ever had the need.

Just create an artificial scope with do … end, and declare private members as ‘local’ inside that block. Only the methods inside that block will have access to them:

MIT License
Copyright (c) 2011 Enrique García Cota

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.