Lua's object-oriented-Multiple inheritance, privacy

Source: Internet
Author: User

This article was reproduced in:http://www.benmutou.com/archives/1800

Multiple inheritance and privacy in Lua may be less or less of a personal use.

Originally want to lazy do not write this article, because I just bought a drift board today, even start have not learned Ah, want to learn a little more.

Cough, in the spirit of perseverance, responsible for the end attitude, I still decided to write a few words ~ (Jor: Casually write a few tons of meaning ah?!) )

1. Multiple inheritance find a field in multiple classes

I found these high (Shen) Jing (Bing) People really very powerful, this technique can be thought of, very admire.

In fact, multiple inheritance is nothing special, unless the two classes that will be inherited have the same function name and attributes, otherwise, it is easy to handle.

Is it not easy to find a field in more than one table? The inheritance in Lua is to find a field in someone else's table that doesn't exist.

So, the difference between single inheritance and multiple inheritance is here, one is to find only one table, and the other is to find two or more table.

Let's take a look at how to find a field from 2 or more table, the following code:

function Search (classes, key) fori =1, #classes DoLocal Value=Classes[i][key]; ifValue ~=Nil Thenreturnvalue; End Endendlocal T1= {Name ="hehe"};local T2= {game ="W.H.O."};p rint (search ({t1, t2},"Game"));

The classes parameter here is a table, which stores multiple table, which is the class we want to inherit.
And key is the field to look for.

Just go through all the table, determine if the field is in a table, and return this value after it is found.

Our test code is to find the game from T1, T2 , T1, T1 can be seen as two classes.

The output results are as follows:

[Lua-print] Who
2. Multiple inheritance creation inherits subclasses of multiple classes

Just the search function is simple, right? Don't rush to be happy, it's just warming up, the function of actually creating multiple inheritance is more complex.

The following code:

function Createclass (...) Local parents= {...}; Local Child= {}; --sets the meta-table of the class setmetatable (child, {__index=function (table, key)returnSearch (parents, key); End})--add a new function to the class to create the object function child:New() o= {};        Setmetatable (o, child); Child.__index=Child ; returno; End--returns a subclass that inherits multiple classesreturnChild;end

The Createclass function is used to create a subclass that inherits more than one class, a little bit more complex and slowly analyzed:

1) The parameter is a mutable parameter, and we are going to pass in a number of inherited classes as parameters.

2) Parents is used to save these inherited classes.

3) Create a new table--child, which is the subclass that we want to inherit multiple classes

4) Set the meta table for child, and set the __index meta method, the __index meta method can be a function, and when it is a function, its arguments are the table to which the meta table belongs, and the name of the field to find.

5) We call the search function in the __index meta method function to find the desired field from multiple parent classes. As a result, when a function of child is called, it is looked up from the various parent classes, which has completed the work of inheritance.

6) Next we are familiar with the new function, used to create child subclasses, the implementation of the same way as the previous one said, if you forget, you can read this article: http://www.benmutou.com/archives/1791

7) finally returned to child, and everything was done.

Seems to be very complex, in fact, it is the application of __index.

Let's test it, here's the code:

--an elf class Tsprite={} function Tsprite:hello () print ("who's hello! with you? "); End Function Tsprite:New() o={} setmetatable (o, self); Self.__index=Self ; returno; End--a bullet class Tbullet={} function Tbullet:fire () print ("don't move, move again, I can't aim! "); End Function Tbullet:New() o={} setmetatable (o, self); Self.__index=Self ; returno; End--subclass of two classes inherited local Bulletsprite=Createclass (Tsprite, Tbullet); --object of subclass local Bsprite= Bulletsprite:New();    Bsprite:hello (); Bsprite:fire ();

There are two classes created here: Tsprite and Tbullet.

Then call the Createclass function to create a subclass that inherits the Tsprite and Tbullet.

Finally, the object of the subclass is created, calling the object's Hello and fire functions.

The output results are as follows:

[lua-Print] Who's with you hello! [LUA-print] Don't move, move, I'll stop!
3. Privacy of Classes

Here is a technique unrelated to multiple inheritance, which is privacy.

For Java, C + + and other languages, we are very familiar with public, private, protected and other keywords.

These keywords allow encapsulation to be possible.

Then there is no privacy in Lua, and the class is a table,table all the fields are callable, without saying what is public and which is private.

If you have some functions and properties that you do not want to be called externally, you can, but this implementation looks awkward:

function Createtsprite () Local self= {Name ="Benmutou"}; Local function MyBus () print ("MyBus is my own function, you can't call directly"); End local function mygame () print ("Mygame is my own function, you can't call directly"); End local function hello () print ("Hello:");    MyBus (); End local function hi () print ("Hi:");    Mygame (); End local function setName (newName) self.name=NewName; Endreturn{Hello = hello, hi = Hi, setName =Setname};end

We have no need to use a colon to define a function, and the name, MyBus, and mygame of this class are not expected to be directly called externally.

When the Createtsprite function is called, a new table is returned, which contains only a few fields that are functions or properties that can be called directly from outside .

Take a look at the test code:

Local SP = createtsprite ();    Sp.hello ();    Sp.hi ();

The output results are as follows:

[lua-Print] Hello:[lua-print] MyBus is my own function, you can't call [LUA-print] Hi:[lua-print] Mygame is my own function, you can't call directly

In this way, the objects we create can only use the Hello, Hi, setname functions.

The other name, MyBus, and Mygame can only be called through the functions that can be used, not directly.

This will complete the privacy of the.

However, I am a bit confused, because it is not much like a class of the look.

4. End

Well, for the object-oriented content, this is a temporary introduction.

It is possible to introduce a comparative basis for the purpose of consolidating the LUA Foundation.

Lua's object-oriented-Multiple inheritance, privacy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.