Lua(3) ——Cocos之_语法糖class
更新:HHH   时间:2023-1-7


【唠叨】

    在使用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 cls

end


    在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() 中进行声明即可。



返回游戏开发教程...