zoukankan      html  css  js  c++  java
  • lua 定义类 就是这么简单

    在网上看到这样一段代码,真是误人子弟呀,具体就是:

    lua类的定义

    代码如下:

    local clsNames = {}
    local __setmetatable = setmetatable
    local __getmetatable = getmetatable
    
    function Class(className, baseCls)
        if className == nil then
            BXLog.e("className can't be nil")
            return nil
        end
    
        if clsNames[className] then
            BXLog.e("has create the same name, "..className)
            return nil
        end
        clsNames[className] = true
        
        local cls = nil
        if baseCls then
            cls = baseCls:create()
        else
            cls = {}
        end
        cls.m_cn = className
    
        cls.getClassName = function(self)
            local mcls = __getmetatable(self)
            return mcls.m_cn
        end
    
        cls.create = function(self, ...)
            local newCls = {}
            __setmetatable(newCls, self)
            self.__index = self
            newCls:__init(...)
            return newCls
        end
    
        return cls
    end

    这个代码的逻辑:
    1.创建一个类,其实是创建了一个父类的对象。
    然后指定自己的create.

    2.创建一个类的对象,其实就是创建一个表,这个表的元表设置为自己。然后调用初始化。

    上面是错误的思路。
    ----------------------------------------

    我的理解:
    1.创建类:创建一个表, 且__index指向父类。

    2.创建对象:创建一个表,元表设置为类。

    ### 就是这么简单,只要看下面的cls 和inst 两个表就可以了。

    我来重构,如下为核心代码:

    function Class(className, baseCls)
        local cls = {}
        if baseCls then
            cls.__index = baseCls
        end
    
        function call(self, ... )
            local inst = {}
            inst.__index = self--静态成员等。
            setmetatable(inst, self)
            inst:__init(...)
            return inst
        end
        cls.__call = call
    
        return cls
    end
  • 相关阅读:
    nrf51822蓝牙芯片ble_app_proximity程序总结
    创新学分材料
    毕业论文 一定要自己写 切记不可抄袭​
    Shell awk 求标准差
    Java程序执行Linux命令(JSP运行其他程序)
    SFTP无法连接 Connection closed by server with exitcode 127
    IE开发人员工具手册
    jQuery plugins
    Google maps api demo 2
    Google maps api demo
  • 原文地址:https://www.cnblogs.com/hackerl/p/8710181.html
Copyright © 2011-2022 走看看