Cocos2d-Lua02Lua object-oriented

Source: Internet
Author: User

Cocos2d-Lua02Lua object-oriented
1 object-oriented 1.1 in Lua

Lua is not an object-oriented language, but he has an object-oriented idea. In lua, the object orientation is pseudo-object-oriented, and the object orientation must be table-based.

A table simulates an object-oriented programming. A table can also be viewed as an object. Like other language objects, a table has its own identifier (self) and has its own lifecycle. This case demonstrates object-oriented in lua.

1.2 Solution

First, use table to implement object-oriented.

Then, use self to obtain the current lable object.

Next, use the symbol to implement the implicit test parameter self when declaring the function.

Finally, return an object through require and call this object method.

Step 1

To implement this case, follow these steps.

Step 1: Use table to implement object-oriented

First, define a table-type data Account, then declare the label object, and call the method through the object. The Code is as follows:

 
  1. Accout = {balance = 0}
  2. FunctionAccout. count (v)
  3. Print ("value is" .. v)
  4. End
  5. -- Declare the label object (variable) accout
  6. Accout = Accout
  7. -- Call methods through objects
  8. Accout. count (1000)

The effect in the editor is shown in-13:

Figure 13

 

Step 2: Use self to obtain the current lable object

Through the object call method, the displayed object "accout" is passed into the function (display incoming self). You can also use the colon call method to implicitly import the self Object Code as follows:

 
 
  1. Accout = {balance = 10}
  2. -- Display incoming self
  3. FunctionAccout. count (self, v)
  4. Self. balance = self. balance + v;
  5. Print ("value is"... self. balance)
  6. End
  7. -- Declare the label object (variable) accout
  8. Accout = Accout
  9. -- Pass the table accout to the function (display incoming self) through the object call method)
  10. Accout. count (accout, 1000)
  11. -- The self object can also be passed in through the: Call method.
  12. Accout: count (2000)

The effect in the editor is shown in-14:

Figure 14

Step 3: Use a colon to declare implicit parameters of a function

You can use the colon symbol to implicitly pass in the self object. The Code is as follows:

 
  1. Accout = {balance = 10}
  2. -- Pass self through: Symbol
  3. FunctionAccout: count (v)
  4. Self. balance = self. balance + v;
  5. Print ("value is"... self. balance)
  6. End
  7.  
  8. -- Declare the label object (variable) accout
  9. Accout = Accout
  10. -- The self object can also be passed in through the: Call method.
  11. Accout: count (2000)

The effect in the editor is shown in-15:

Figure-15

 

Step 4: return objects through require

Use require to return an object and call this object method. The Code is as follows:

 
 
  1. Class = require ("myClass ")
  2. -- The function is written outside the brackets of the table.
  3. Class: showName ()
  4. -- The function is written in brackets of the table.
  5. Class. show (class)

The effect in the editor is shown in-16:

Figure 16

------------- "Require (" XXX ") -- only executes once, avoiding repeated execution

1.4 complete code

In this case, the complete code is as follows:

 
 
  1. -- [[Lua is not an object-oriented language, but he has an object-oriented idea.
  2. In lua, the object orientation is pseudo-object-oriented, and the object orientation must be table-based,
  3. It is table that simulates an object-oriented programming. table can also be seen as an object,
  4. Similar to other language objects, a self has its own lifecycle.]
  5.  
  6. -- 1. Use table to implement object-oriented
  7. Accout = {balance = 0}
  8.  
  9. FunctionAccout. count (v)
  10. Print ("value is" .. v)
  11. End
  12.  
  13. -- Declare the label object (variable) accout
  14. Accout = Accout
  15. -- Call methods through objects
  16. Accout. count (1000)
  17.  
  18.  
  19.  
  20. -- 2. Get the current lable object through self
  21. Accout = {balance = 10}
  22. -- Display incoming self
  23. FunctionAccout. count (self, v)
  24. Self. balance = self. balance + v;
  25. Print ("value is"... self. balance)
  26. End
  27.  
  28. -- Declare the label object (variable) accout
  29. Accout = Accout
  30. -- Pass the table accout to the function (display incoming self) through the object call method)
  31. Accout. count (accout, 1000)
  32. -- The self object can also be passed in through the: Call method.
  33. Accout: count (2000)
  34.  
  35.  
  36. -- 3. Use the symbol to implement the implicit test parameter self when declaring the function.
  37. Accout = {balance = 10}
  38. -- Pass self through: Symbol
  39. FunctionAccout: count (v)
  40. Self. balance = self. balance + v;
  41. Print ("value is"... self. balance)
  42. End
  43.  
  44. -- Declare the label object (variable) accout
  45. Accout = Accout
  46. -- The self object can also be passed in through the: Call method.
  47. Accout: count (2000)
  48.  
  49.  
  50. -- 4. Return an object through require and call this object Method
  51. Class = require ("myClass ")
  52. -- The function is written outside the brackets of the table.
  53. Class: showName ()
  54. -- The function is written in brackets of the table.
  55. Class. show (class) 2. metadatabase method and metadatabase method: a function that operates between two types of variables, for example, 1. the addition of a number may be just a function: 1 + 1 ---> add () ---> the add function is used to calculate the result of adding two numbers to the de2.table type? ---> There are no two metamethods in Lua: {} +! Metadata table: A table used to store metadata. It is a series of operations predefined by a table. After adding two tables, Lua will first check whether the two tables have retriable, and then check whether the _ add method exists in the retriable. If any operation is performed in the _ add method, otherwise, an error is returned. For example, if you want to add two table types, an error is reported when running the command directly. However, Lua allows you to modify the metadata table as follows:

    A metadatabase is actually a table value. Therefore, we only need to create a new table and add the metadatabase method.

    For example, the meta method of the addition operation is __add, which is defined by Lua.

    As long as the meta table of a value contains the _ add meta method, you can use the + number for calculation.

     

    The following code:

     
      
    1. -- Create a metadata table
    2. Local mt = {};
    3. Mt. _ add = function (t1, t2)
    4. Print ("the result of adding two tables is... Good Study, Day Up! ");
    5. End
    6.  
    7. Local t1 = {};
    8. Local t2 = {};
    9.  
    10. -- Set a new metadata table for the two tables
    11. Setretriable (t1, mt );
    12. Setretriable (t2, mt );
    13.  
    14. -- Perform Addition
    15. Local result = t1 + t2;

First, create a table variable mt and add an element _ add to the table. This table is qualified as a table.

Create two new table variables and use the setretriable function to set a new table metadata. At this time, the two table variables use mt as the metadata table.

Finally, the addition operation is performed on t1 and t2, And the _ add meta method is searched from the meta table. If yes, the meta method is called to add the two variables.


Each value in Lua has or can have a metadata table, but table and userdata can have independent metadata tables. Values of other types can only share the elements of their types. For example, a string uses a string meta table. Note: When creating a table, Lua does not create a readable table. You must use setretriable to set the metadata table. The setretriable parameter allows any table, including the table to be assigned a value. ------ Check whether a variable has a metadata table: print (getretriable (a) -- nil indicates that there is no important metadata method in the metadata table Lua: __eq is equal to, _ lt is less than, _ le is less than or equal to, _ add: addition, _ sub: subtraction, _ mul: Multiplication, _ div: division, _ unm: inverse number, _ mod: modulo, _ pow: Power Multiplication, _ index function (table, key), _ newindex function (table, key, value), _ tostring is called by print (), and _ resumable can be used to hide mt.

You only need to assign new functions to these functions when customizing the metadata table.

Lua accesses the table element. First, it uses the _ index meta method to find whether this function exists (if not, nil is returned); __ the index value can be a table directly, it can also be a function (if it is a table, the table is used as an index for query; if it is a function, the table and the missing fields are used as parameters to call this function)

 

Example 1,

Create a custom meta table (that is, a table variable) to define some operations:

 
  1. -- Create a metadata table
  2. Local mt = {};
  3. Mt. _ add = function (s1, s2)
  4. Local result = "";
  5. If s1.sex = "boy" and s2.sex = "girl" then
  6. Result = "qingmei Bamboo ";
  7. Elseif s1.sex = "girl" and s2.sex = "girl" then
  8. Result = "empty or empty ";
  9. Else
  10. Result = "hard-hitting"
  11. End
  12.  
  13. Return result;
  14. End
 

 

In fact, this is basically the same as the example in the previous section. I just want to talk about it once. The usage is as follows:

 
  1. -- Create two tables, which can be imagined as objects of two classes
  2. Local s1 = {
  3. Name = "Hello ",
  4. Sex = "boy ",
  5. };
  6. Local s2 = {
  7. Name = "Good ",
  8. Sex = "girl ",
  9. };
  10.  
  11. -- Set a new metadata table for the two tables
  12. Setretriable (s1, mt );
  13. Setretriable (s2, mt );
  14.  
  15. -- Perform Addition
  16. Local result = s1 + s2;
  17.  
  18. Print (result); example 2. Window = {} Window. mt = {} Window. prototype = {x = 0, y = 0, width = 100, height = 100} Window. mt. _ index = function (table, key) return Window. prototype [key] end function Window. new (t) setretriable (t, Window. mt) return tend -- Test w = Window. new {x = 10, y = 20} print (w. the usage of heigth) _ newindex is basically the same as that of Example 2. The difference is that _ newindex is used for table update, __index is used for table query operations. When a value is assigned to an index that does not exist in the table, the _ newindex meta method is called. The combination of _ index and _ newindex can implement a lot of functional encapsulation: With the metadata table, the Lua class encapsulation will become very easy. You only need to add a retriable to the table and set the _ index method. For example: People = {age = 18} function People: new () local p = {} setretriable (p, self) self. _ index = selfreturn pend function People: groupUp () self. age = self. age + 1 print (self. age) end -- Test p1 = People: new () p1: growUp () -- 19p2 = People: new () p2: growUp () -- 19 -- [[the running results show that: the age members of the two objects are completely independent, and all the People-related methods can be invisible to the outside. In this way, the class encapsulation in the object-oriented model is fully realized --] inheritance: inheritance is an essential part of object-oriented systems. We still use People in the above example to demonstrate the methods for implementing inheritance in Lua. Create a People instance Man, and then override the People method with the same name on Man: Man = People: new () function Man: growUp () self. age = self. age + 1 print ("man's growUp :".. self. age) end -- Test man1 = Man: new () man1.growUp () -- man's growUp: 19 polymorphism: Lua does not support function polymorphism, but supports pointer polymorphism, lua is supported by its dynamic type. Person = People: new () person: growUp () -- People's growUp: 19 person = Man: new () person: growUp () -- Man's growUp: 19

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.