Object-oriented-class and inheritance of Lua

Source: Internet
Author: User

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

Finally, in Lua's object-oriented programming, I believe most of the people who are currently learning Lua are trying to develop mobile online games.
And it's basically all about the hot update feature of the scripting language, so full scripting has become very popular.

For the less widespread LUA (as opposed to C + +, Java and other mainstream languages), it takes a short time to get started on the game, which is not easy for beginners.
So we are more accustomed to continue to use object-oriented thinking to toss Lua ~

Well, no nagging, I don't like nagging. (Jor: Yes Yes, you are not nagging at all, hurry up!) )

1. Objects of the class

As for how to create a class, it is clear that it is a table.

So, how do you use this class to create multiple objects?

You can use the meta-table and meta-methods.

The following code:

Tsprite ={x=0, y=0,} function tsprite:setposition (x, y) self.x=x; Self.y=y; End Function Tsprite:New() o={} setmetatable (o, {__index=Self }); returno; End Local Who1= Tsprite:New(); Local Who2= Tsprite:New(); Who1:setposition (1,2); Who2:setposition ( -,6); Print ("Who1 Coordinates (".. who1.x.",".. Who1.y.")"); Print ("Who2 Coordinates (".. who2.x.",".. Who2.y.")");

Notice the new function of the tsprite, create a table in the function, and set a meta-table for the new table, the __index meta-method of the meta-table is tsprite itself, and finally returns the new table.

As a result, all new table generated through new can use Tsprite's functions and individual field properties (because the value of __index is Tsprite).

Therefore, we created Who1 and Who2 with the new function, and called their setposition functions, and finally, the X and Y values of who1 and Who2 are different.

This is the object of the class.

2. The __index of class objects are all the same tsprite, why can x and Y values be different?

Do not know that there is no such a doubt, that is, why Who1 and Who2 x, Y is not the same, they ultimately call is not the SetPosition function? Does calling self.x end up not calling the X-value of Tsprite?

There's a bit of confusion here, and there's no problem with the rationale:

1). When there is no setposition in the Who1, go back to __index in the meta-method and find the SetPosition function of Tsprite.

2). In the SetPosition function, self.x = x is used, and self is the absence of the X field in Who1,who1, so if we want to print the value of self.x, we actually print the X value of Tsprite .

3). But, notice, but it's coming. __index meta-method is used for invocation, not for assignment, so, self.x = x This sentence, in fact, just give who1 this table x field assignment, Who1 itself does not exist x field, at this time to assign value, so who1 there is an X field, Later Who1 will not go to Tsprite to find the X field.

4). Therefore, when assigning operations to the X and Y fields of Who1 and Who2, the tsprite is not affected at all.

3. Save resources-using tsprite as a meta-table

Let's take a closer look at the new function, and when we set the meta table for the new table, we re-created a meta-table: Setmetatable (o, {__index = self});

In doing so, each time a new object is called, a new meta-table is created, although the expense seems to be negligible, but you, with Obsessive compulsive disorder, must like the following code:

function Tsprite:new()        = {}        setmetatable (o, self);         = self ;         return o;    End

In this new function, self is used as the meta-table, and self is used as the value of the __index.

Such a look, a little around, I like the people around, so I can nag:

1). When calling the new function, self is actually the tsprite itself, here can be replaced with tsprite, but, in order to pave the way for the future, here is still the use itself.

2). Self.__index = self, do not be frightened by this code, in fact, it is still the same thing, set the meta-table __index meta-method, here is equivalent to Tsprite.__index = Tsprite.

3). Tsprite yourself as the value of __index? Really no problem, Tsprite is also a table,table can be used as a meta-table, the meta-table can have a __index meta-method, which has no heroes.

4). So, with this tip, we avoid creating a new meta-table every time we call the new function.

4. Rich second generation What I don't like--inherit

We always joke rich second generation, but who deep in the heart do not want to be a rich second generation it ~

Like me this is determined to rely on their own to become rich generation of people, not much ~ (Jor: Ah i yuck! )

So how do you implement inheritance in Lua ? Very simple, but need to think carefully, the following code:

Tsprite ={x=0, y=0,} function tsprite:setposition (x, y) self.x=x; Self.y=y; End Function Tsprite:New() o={} setmetatable (o, self); Self.__index=Self ; returno; End Local Moneysprite= Tsprite:New(); function moneysprite:setposition (x, y) print ("Oh, I am rich second generation, there is no need to change. "); End

Tsprite still remains unchanged, but let's look at Moneysprite, which, as previously understood, is an object of Tsprite.

It's just that the term "object" is our own, and it's actually a table.

At this point, we have modified the Moneysprite setposition function, so, when calling Moneysprite's SetPosition function, it has nothing to do with Tsprite.

But, this is not the point, the focus is the following code:

Local who = Moneysprite:new();    Who:setposition (6);       Print ("whocoordinates (" ",""") ");

We re-called the new function of Moneysprite to create an object.

What is the situation? The key is the code in the new function, who is the self in the new function?

The new function is called by moneysprite, so self is moneysprite.

So the new object's meta-table is Moneysprite, the __index of the meta-table is also moneysprite.

So ~ ~ It is amazing to call the SetPosition function of the WHO, but it is also called the Moneysprite setposition function.

Thus, the WHO is the object of Moneysprite, and Moneysprite is Tsprite subclass.

Let's take a look at the output:

[lua-Print] Oh, I am rich second generation, there is no need to change. [LUA-print] who coordinates (0,0)

What do you think? the implementation of inheritance is also very simple, right?

If the meta-table, meta-method, self is unfamiliar, it may be a time to understand, it's OK, think a little more, or the next day back to think, will be enlightened.

5. End

Unconsciously this series of articles have been written 20, it is too unexpected to me.

I can insist on it, but the effect of writing the article is really good, 1 hours per night is also worthwhile.

At the very least, my understanding of the basics of LUA has strengthened.

All right, keep going. (Jor: So say AH ~! Why do you use ellipses every time, not more to express your determination with exclamation mark ... )

Object-oriented-class and inheritance of Lua

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.