Lua object-oriented two methods

1, with element method and the table element

lua object-oriented programming is based on the metatable, meta-membered table __index method implemented
by a table element __index element method, a table is provided a method of __index element to another table, then the latter method was inherited former

If you visit a lua table element does not exist, it will trigger a lookup mechanism lua, is by virtue of this mechanism to be able to implement object-oriented
step of finding yuan summary table:
Step 1. Look in the table, if found , the element is returned, not found proceed to step 2
step 2 determines whether the table has a table element, if there is no table element, returns nil, then continue with step meta table 3
step 3. Analyzing methods __index membered table there, If __index method is nil, nil is returned; if __index is a table, then repeat steps 2, 3; __index If the method is a function, the function is called, and returns the return value of the function

  • Element like a spare table lookup table, table A table assumes element is B, then A is not found in attempts to find something in B, the table element is provided as a function of
  •  setmetatable (A, B), so that they are set to Table B Element Table A, when A is not to find a variable B will be found in
  • __Index element method are used to determine a table lookup method, when a table element
  • Object-oriented package

- set a new target of the metatable
setmetatable (tempObj, Class)

  • For object inheritance and polymorphism

Parent Class: - Element Method for setting the metatable __index, their point table Class
Class Class .__ = index
- new objects provided metatable,
setmetatable (tempObj, Class)
subclass: - Element Set table Class
setmetatable (SubClass, class)
- element method for setting the metatable __index, their point table SubClass
SubClass .__ index = SubClass

2, directly to the members of the base class subclasses deep copy

: Foreign only class function, parameter is the name of the base class returns a derived class object data. Function returns the passed in the base class, to get the corresponding metadata table is initialized membered derived object table, so that the code is running, does not need to look up the dynamic defect that when an object is created to do so will consume more time.

 

 

Guess you like

Origin www.cnblogs.com/wwhhgg/p/12606677.html