Lua object-oriented and inheritance _lua

Source: Internet
Author: User
Tags lua

Finally come, object-oriented programming in Lua, I believe that most of the people who are learning Lua are trying to develop mobile online games.

And it's basically all about the hot-update features of the scripting language, so the full script development becomes very popular.
For the less popular LUA (in contrast to C + +, Java and other mainstream languages), need to play a short time to develop games, for beginners is not easy.

So people are more accustomed to continue to use object-oriented thinking to toss LUA it ~

OK, no nagging, I hate nagging. (Jor: Yes yes, you don't nag at all, just talk!) )

1. Object of Class

As for how to create a class, it is already clear that it is just a table.
So, how do you implement this class to create multiple objects?
You can use the Meta table and the Meta method.

The following code:

Copy Code code as follows:

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});
return o;
End

Local who1 = Tsprite:new ();
Local Who2 = Tsprite:new ();
Who1:setposition (1, 2);
Who2:setposition (44, 6);
Print (Who1 coordinates (...). who1.x.. "," .. Who1.y.. ")");
Print (Who2 coordinates (...). who2.x.. "," .. Who2.y.. ")");

Notice that the new function of Tsprite, which creates a new table, and sets a meta table for the new table, the __index method of the meta table is the tsprite itself, and finally returns the table.

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

So 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 X and Y values can be different?

Do not know if you have 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 not ultimately call the X value of Tsprite?
There's a bit of confusion here, and there's no problem with that:

1. When there is no setposition in the Who1, go back to __index the meta method and find the Tsprite setposition function
2. In the SetPosition function, the self.x = x is used, at which time self is who1,who1 there is no X field, so if we want to print the self.x value, we actually print the Tsprite x value
3). But, notice, but come on. The __index method is used for invocation, not for assignment, therefore, self.x = x This sentence, actually only to who1 this table's X field assignment, Who1 itself does not exist x field, at this time assigns value to it, then Who1 has the X field, Later Who1 will not go to the Tsprite to find X field.
4). Therefore, the Who1 and Who2 x, y fields are assigned to the operation, it does not affect the tsprite.

3. Saving resources-using tsprite as a meta table

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

In so doing, a new meta table is generated each time a new object is invoked, although the expense may seem negligible, but you, who have OCD, must love the following code:

Copy Code code as follows:

function Tsprite:new ()
o = {}
Setmetatable (o, self);
Self.__index = self;
return o;
End

In this new function, use self as the meta table, and then use self as the __index value.

It's a bit of a detour, and I like it when people can't get around, so I can nag again:
1. When invoking the new function, self is actually the tsprite itself, which can be completely replaced with tsprite, but in order to pave the way for the future, here is to use self.
2. Self.__index = self, do not be frightened by this code, in fact, it is the same thing, set the meta table __index method, here is equivalent to Tsprite.__index = Tsprite.
3. Tsprite own as the value of __index no problem? No problem, Tsprite is also a table,table can be as a meta table, the meta table can have __index method, this is not a hero.
4. So, with this little trick, we avoid creating a new meta table every time we call the new function.

4. I don't like the rich generation or the other--inherit

We always joke rich second generation, but who deep inside do not want to be a rich second-generation it ~
Like me this determined to become a rich generation of people, not many ~ (Jor: Ah, I pooh ~! )

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

Copy Code code as follows:

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;
return o;
End

Local moneysprite = Tsprite:new ();
function moneysprite:setposition (x, y)
Print ("Oh, I am a rich second-generation, there is no need to change." ");
End

Tsprite still hasn't changed, but let's take a look at Moneysprite and, as previously understood, it's an object of Tsprite.
It's just that the name "Object" is our own, and it's actually a table.

At this point, we modified the moneysprite setposition function, so the setposition function of the moneysprite is not related to the tsprite.

But that's not the point, the point is the next code:

Copy Code code as follows:

Local who = Moneysprite:new ();
Who:setposition (44, 6);

Print ("Who Coordinates (" ...) Who.x.. "," .. Who.y.. ")");

We then call Moneysprite's new function again 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 at this point?
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 ~! Amazingly, when calling the Who setposition function, it's also called the Moneysprite setposition function.

So, who is the object of Moneysprite, and Moneysprite is Tsprite subclass.

Let's look at the output:

Copy Code code as follows:

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

What do you think? The implementation of the inheritance is also very simple?
If you are unfamiliar with the meta table, the Meta method, and self, you may not understand it for a moment, it doesn't matter, think more for a while, or think again the next day, it will be enlightened.

5. End

Unknowingly this series of articles have been written 20, it is too surprising me.
I can insist on it, but the effect of writing the article is really good, 1 hours a night to pay is also very worthwhile.
At the very least, my understanding of the LUA Foundation is more consolidated.

All right, keep going. (Jor: So say ah ~! Why do I have to use ellipsis every time, with an exclamation point is not more able to express your determination ... )

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.