众所周知,lua没有类这个概念但其通过table实现了面向对象的“类”。在cocos2dx引擎下提供了class(className, ...)函数方法名,因为在脚本开发中这个接口基本都会用来创建一个lua对象,所以很重要。在之前的求职面试中,也有一些公司问到了这个实现的问题,如“lua中定义的class,使用了lua的哪些特性; class方法是如何实现模拟lua继承的呢?”等。

class有三种继承情况,
、第一种是继承一个方法,
local LogoScene = class("LogoScene", function()
    return cc.Scene:create()
end)
、第二种继承一个C语言原生类
local LogoScene = class("LogoScene", cc.Scene)
、继承一个lua类
local LogoScene = class("LogoScene", {})

  下面就3.x逐行源码进行详细分析。

function class(classname, ...)
    local cls = {__cname = classname}
    --多继承
    local supers = {...}
    for _, super in ipairs(supers) do
        local superType = type(super)
        assert(superType == "nil" or superType == "table" or superType == "function",
            string.format("class() - create class \"%s\" with invalid super class type \"%s\"",
                classname, superType))

        if superType == "function" then
            assert(cls.__create == nil,
                string.format("class() - create class \"%s\" with more than one creating function",
                    classname));
            cls.__create = super
        elseif superType == "table" then
            --若有.isclass这个值则说明是从c++转换过来的数据结构
            if super[".isclass"] then
                assert(cls.__create == nil,
                    string.format("class() - create class \"%s\" with more than one creating function or native class",
                        classname));
                cls.__create = function() return super:create() end
            else
                -- lua表
                cls.__supers = cls.__supers or {}
                cls.__supers[#cls.__supers + ] = super
                if not cls.super then
                    cls.super = super
                end
            end
        else
            error(string.format("class() - create class \"%s\" with invalid super type",
                        classname), )
        end
    end
    --lua元表:实现继承的重要元素,__index "查询"当子类搜索自己的函数未果,会按照__index的指引去搜索父类方法)
    cls.__index = cls
     then
        setmetatable(cls, {__index = cls.super}) --索引唯一父类
    else
        setmetatable(cls, {__index = function(_, key)
            local supers = cls.__supers
            , #supers do
                local super = supers[i]
                if super[key] then return super[key] end --遍历索引多个
            end
        end})
    end

    if not cls.ctor then
        -- add default constructor
        cls.ctor = function() end
    end
    cls.new = function(...)
        local instance
        if cls.__create then --C++层/lua方法
            instance = cls.__create(...)
        else
            instance = {}
        end
        setmetatableindex(instance, cls)
        instance.class = cls
        instance:ctor(...)
        return instance
    end
    cls.create = function(_, ...)
        return cls.new(...)
    end

    return cls
end

手游开发之lua的class函数详解的更多相关文章

  1. 手游开发之lua的table 元表的运用

    元表在项目中的运用,其中就包括元方法这点.元方法是指__index和__newIndex,下面我总结下,更详细的例子讲解可以参考<lua程序设计 第2版>的第13章内容.长h短说,简言之有 ...

  2. cocos2dx+lua注册事件函数详解 事件

    coocs2dx 版本 3.1.1 registerScriptTouchHandler             注册触屏事件 registerScriptTapHandler             ...

  3. Python全栈开发之8、装饰器详解

    一文让你彻底明白Python装饰器原理,从此面试工作再也不怕了.转载请注明出处http://www.cnblogs.com/Wxtrkbc/p/5486253.html 一.装饰器 装饰器可以使函数执 ...

  4. android开发之eclipse调试debug模式详解

     之前我写了一个相关的帖子,但是今天看了一个还是写的比我详细,于是我拿过来和大家分享. 1.在程序中添加一个断点 如果所示:在Eclipse中添加了一个程序断点 在Eclipse中一共有三种添加断 ...

  5. cocos2dx+lua注册事件函数详解

    coocs2dx 版本 3.1.1 registerScriptTouchHandler 注册触屏事件 registerScriptTapHandler 注册点击事件 registerScriptHa ...

  6. 【转】Android开发之Bitmap的内存优化详解

    本文来源:转载自: http://mobile.51cto.com/abased-410796.htm 在Android应用里,最耗费内存的就是图片资源.而且在Android系统中,读取位图Bitma ...

  7. android开发之wheel控件使用详解

    出门在外生不起病呀,随便两盒药60多块钱.好吧,不废话了,今天我们来看看wheel控件的使用,这是GitHub上的一个开源控件,用起来十分方便,我们可以用它做许多事情,比如做一个自定义的datepic ...

  8. (转载)【cocos2dx 3.x Lua] 注册事件函数详解

    出处: http://www.2cto.com/kf/201409/338235.html coocs2dx 版本 3.1.1 registerScriptTouchHandler 注册触屏事件 re ...

  9. Android开发之5大布局方式详解

    Android中常用的5大布局方式有以下几种: 线性布局(LinearLayout):按照垂直或者水平方向布局的组件. 帧布局(FrameLayout):组件从屏幕左上方布局组件. 表格布局(Tabl ...

随机推荐

  1. ionic2 vscode运行调试

    一.环境搭建 1,安装ripple模拟器 如果已经注册了淘宝国内镜像使用下面命令 cnpm install -g ripple-emulator 显示结果如下: 2,安装vs code 下载地址htt ...

  2. Redis深入学习笔记(二)client list 命令详解

    Redis的client list 命令可以获取当前连接到redis server端的所有客户端以及相关状态,本篇主要介绍每一个参数的作用. clisnt list 命令输出结果如下: (1)标识:i ...

  3. Redis主从+读写分离中可以在从机读取到过期数据

    参考链接: https://mp.weixin.qq.com/s?__biz=MzIyNzUwMjM2MA==&mid=2247483696&idx=1&sn=c69e364b ...

  4. Java笔记Spring(五)

    C:\apache-tomcat-8.0.36\bin\catalina.bat run [2018-05-23 02:30:31,657] Artifact demo-springmvc:war e ...

  5. 使用Git将本地文件提交到远程仓库

    一 操作准备条件: git远程仓库已经建好了,本地文件已经存在了,现在要将本地代码推到git远程仓库保存. 解决办法如下: 1.(先进入项目文件夹)通过命令 git init 把这个目录变成git可以 ...

  6. ubuntu环境部署项目

    安装python3.6 第一步:sudo add-apt-repository ppa:jonathonf/python-3.6 如果报错为:sudo: add-apt-repository: com ...

  7. C# 反射获取属性值、名称、类型以及集合的属性值、类型名称

    实体类 class Product { public string Id { get; set; } public string Name { get; set; } public List<P ...

  8. 【C语言基础】变量

    1.什么是变量? 变量的本质就是内存中一段储存空间 2.变量为什么必须初始化? 所谓初始化就是赋值的意思 3.如何定义变量 数据类型 变量名 = 要赋的值 举例子: int i = 3:等价于 int ...

  9. Lightgbm 随笔

    lightGBM LightGBM 是一个梯度 boosting 框架,使用基于学习算法的决策树.它可以说是分布式的,高效的,有以下优势: 更快的训练效率 低内存使用 更高的准确率 支持并行化学习 可 ...

  10. python大法好——多线程

    Python 多线程 多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理. 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件 ...