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.