在建立完cocos2d-x的lua項目後,開啟項目的Resources中的extern.lua檔案。裡面有兩個用於物件導向的方法,一個是用於複製,一個是用於繼承。程式碼分析如下
--複製一個對象function clone(object)--用於儲存被訪問過的對象的表 local lookup_table = {} local function _copy(object) if type(object) ~= "table" then--如果類別不等於table,返回當前參數 return object elseif lookup_table[object] then--如果備份表中存在該對象,則直接返回 return lookup_table[object] end local new_table = {}--建立一個新的表 lookup_table[object] = new_table--把即將被訪問過的表存到備份表 for key, value in pairs(object) do--遍曆,賦值 new_table[_copy(key)] = _copy(value) end return setmetatable(new_table, getmetatable(object))--設定元表,用於繼承 end return _copy(object)end--Create an class.--建立類(類名, 父類)function class(classname, super) local superType = type(super)--擷取父類的類型 local cls--定義一個變數,用來儲存新建立的類的屬性和函數 if superType ~= "function" and superType ~= "table" then--如果父類不是function類別或表類別,父類置空 superType = nil super = nil end if superType == "function" or (super and super.__ctype == 1) then--如果父類型是個function或者來自是c++的類 -- inherited from native C++ Object print(superType) cls = {} if superType == "table" then--來自引擎內建的c++類 -- copy fields from super for k,v in pairs(super) do cls[k] = v end- cls.__create = super.__create cls.super = super else--function cls.__create = super end cls.ctor = function() end--構造 cls.__cname = classname--類名 cls.__ctype = 1--指明派生與C++的類 --建立一個用於建立類的執行個體的方法 function cls.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--建立一個屬性,指向cls instance:ctor(...)--構造 return instance end else -- inherited from Lua Object if super then--如果父類不為空白 cls = clone(super)--把類複製,放到cls中 cls.super = super--建立一個屬性,指向父類 else cls = {ctor = function() end}--否則建立一個空的建構函式 end cls.__cname = classname--建立一個屬性,指明類的名稱 cls.__ctype = 2 -- lua 指明繼承自lua自訂的表 cls.__index = cls --把__index指向自己,用於形成一個繼承的原型鏈 --建立一個用於建立類的執行個體的方法 function cls.new(...) local instance = setmetatable({}, cls)--建立一個空表,並設定它的元表為cls,即繼承cls instance.class = cls--建立一個屬性,指向cls instance:ctor(...)--調用建構函式 return instance end end return clsend測試案例如下
在hello.lua檔案中加入如下代碼
--引入extern.lua require "extern" --test local function test() local luaTable = {x=1, y=2} local N = class("N", luaTable) cclog("繼承lua自訂的表,訪問父類的x屬性值:x="..N.x) local testSprite = function () return CCSprite:create("farm.jpg") end local M = class("M", testSprite) local m = M:new() m.customField = "customField" m:setOpacity(100) cclog("用C++本地類的方式繼承,訪問父類修改後的屬性:"..m:getOpacity()) cclog("訪問子類屬性:"..m:getOpacity()) end test()
運行,結果如下