Lua study note 7-Lua is also object-oriented

Source: Internet
Author: User
Tags pprint

What is Lua's face object? Yes. It has object-oriented operations. Let's look at a simple example:

Ctest = {CNT = 0} </P> <p> function ctest: New (o) <br/> O = O or {}< br/> setretriable (O, self) <br/> self. _ Index = self <br/> return o <br/> end </P> <p> function ctest. add (self, v) <br/> self. CNT = self. CNT + v <br/> end </P> <p> function ctest: pprint () <br/> Print ("ctest... ") <br/> end </P> <p> C1 = ctest <br/> c1.add (C1, 10) <br/> Print (c1.cnt) </P> <p> C1: add (99) <br/> Print (c1.cnt) <br/> C1: pprint () <br/> Print ("/N ")

 

Generally, this or self is used to point to the current object. Python is used to. It is consistent with Python and expressed by self. In Lua, the self parameter can be omitted using the colon syntax. In the preceding example, C1: pprint () is equivalent to c1.pprint (C1 ).

 

 

If you have object-oriented features, you must inherit from them:

Dtest = ctest: New () <br/> function Dtest: pprint () <br/> Print ("Dtest... ") <br/> end </P> <p> d1 = Dtest: New {CNT = 2009} <br/> Print (d1.cnt) <br/> d1.pprint () <br/> Print ("/N ")

Dtest inherits from ctest and overwrites the pprint method.

 

 

With object-oriented features, encapsulation is indispensable:

Function Etest (initcnt) <br/> Local Self = {CNT = initcnt} </P> <p> Local add = function (v) <br/> self. CNT = self. CNT + v <br/> end </P> <p> Local pprint = function () <br/> Print "Etest... "<br/> end </P> <p> return {<br/> Add = add, <br/> pprint = pprint <br/>}< br/> end </P> <p> e1 = Etest (0) <br/> e1.pprint () <br/> Print (e1.cnt) -- CNT cannot be accessed, CNT is a private variable

If you have a good understanding of JavaScript, you can see the above encapsulated code as JavaScript, and the behavior of JavaScript encapsulation is almost the same.

 

 

 

 

 

 

 

 

 

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.