Lua(3) ——Cocos之_語法糖c
- 2020 年 1 月 6 日
- 筆記
【嘮叨】
在使用Lua的時候,cocos2d-x為我們提供了一個 class(classname, super) 這個函數。
它可以讓我們很方便的定義一個類,或者繼承cocos2d-x的某個類。
PS:class()是cocos2d-x為我們封裝的函數,本身Lua沒有這個函數。
基於Lua 5.1。
【Demo下載】
https://github.com/shahdza/Cocos_LearningTest/tree/master/Lua%E4%B9%8Bclass%E7%B1%BB
【class】
class函數是在"cocos2d-x-3.2/cocos/scripting/lua-bindings/script/extern.lua"中定義的。
— Create an class.function class(classname, super) local superType = type(super) local cls if superType ~= "function" and superType ~= "table" then superType = nil super = nil end if superType == "function" or (super and super.__ctype == 1) then — inherited from native C++ Object cls = {} 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 end cls.ctor = function() end cls.__cname = classname cls.__ctype = 1 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 instance:ctor(…) return instance end else — inherited from Lua Object if super then cls = clone(super) cls.super = super else cls = {ctor = function() end} end cls.__cname = classname cls.__ctype = 2 — lua cls.__index = cls function cls.new(…) local instance = setmetatable({}, cls) instance.class = cls instance:ctor(…) return instance end end return clsend |
---|
在Lua中類的概念就是table表,而上面的函數程式碼主要做的就是對父類super的表進行拷貝,然後再定義了兩個函數 cls.new(…) 和 cls:ctor(…) 。如果我們不了解上面的程式碼,也是沒有關係的,只要我們會使用它就夠了。
0、使用方法
> 定義一個類:cls = class("類名","父類")
> 創建實例 :obj = cls.new()
> 初始化函數:cls:ctor() 在創建實例的時候,會自動調用
只要掌握這三步驟,對於我們cocos2d-x的開發已經夠用了!
1、創建基類
首先創建一個Hero類,然後重寫Hero類的初始化函數Hero:ctor() 。
再創建一個Hero類的實例對象Hero.new() ,會自動調用初始化函數Hero:ctor() 。
測試輸出。
注意:其中ctor()中出現的 self 為實例對象本身,就相當於C++類中的 this 。

2、繼承父類
在cocos2d-x開發中,經常需要繼承引擎中的類,如Layer、Sprite等。
這裡舉例,將上面的Hero類修改一下,繼承自Sprite。

3、再舉個例子:繼承Layer類
我一般習慣在 ctor() 中只聲明一些類的成員變數。
然後再自定義一個函數 create() ,將 new() 進行封裝,然後在 create() 中調用 init() 函數進行實例對象的初始化工作。
這樣的好處就是:在使用上就和我在C++中的使用的方式一樣了。
3.1、定義一個繼承於Layer的類

3.2、使用方法
> 創建包含GameLayer層的Scene場景:GameLayer:createScene()
> 創建一個GameLayer層———–:GameLayer:create()
> 而在創建GameLayer時,也會調用自定義的初始化函數 init()
> 類的成員變數,均在 ctor() 中進行聲明即可。