Cocos2dx-lua function. Lua defines the class method, allowing Lua implementation to inherit as beautiful and convenient as a traditional language
View Definition
Function class (classname, super) Local supertype = type (Super) Local CLS -- if the parent class is neither a function nor a table, it indicates that the parent class is null if supertype ~ = "Function" and supertype ~ = "Table" then supertype = nil super = nil end -- if the parent class type is a function or a C object if supertype = "function" or (super and super. _ ctype = 1) then -- inherited from native C ++ object CLS ={} -- if the parent class is a table, copy the Member and set the Inheritance Information of this class. If it is a function type, set the constructor and ctor function if supertype = "table" then -- Copy fields from super for K, V in pairs (Super) Do CLS [k] = V end Cls. _ create = super. _ create Cls. super = super else Cls. _ create = super Cls. ctor = function () end -- set the type name Cls. _ cname = classname Cls. _ ctype = 1 -- Define the function for creating an instance of this type as the base class constructor and copy it to the subclass instance -- and call the ctor method function CLS of the Child number. new (...) local instance = Cls. _ create (...) -- Copy fields from class to native object for K, V in pairs (CLS) Do instance [k] = V end instance. class = CLS instance: ctor (...) return instance end else -- if it is inherited from a normal Lua table, set the prototype, after the instance is constructed, the ctor Method -- inherited from Lua object if super then CLS ={} setretriable (CLS, {__ Index = super}) CLS is also called. super = super else CLS = {ctor = function () end} end Cls. _ cname = classname Cls. _ ctype = 2 -- Lua Cls. _ Index = CLS function Cls. new (...) local instance = setretriable ({}, CLs) instance. class = CLS instance: ctor (...) return instance end return clsend
Write a test code. Pay attention to the error section.
local Base = class(‘Base‘)Base.__index = Basefunction Base:ctor(id) print(‘Base:ctor‘,id) self.id = idendlocal ExtBase = class(‘ExtBase‘,Base)ExtBase.__index = ExtBasefunction ExtBase:ctor(id) --Base:ctor(id) super(self,id) print(‘ExtBase:ctor‘,id)end
Affected by the traditional language, the base class constructor will be called in the subclass. In fact, this causes the type itself to be passed in as an object instance.
As a result, self points to the type itself (also a table)
That's all we can do.
Base. ctor (self, ID)
A little ugly. encapsulate the super function and it looks nice ..