lua实现类

脚本如下

--Class.lua  位于Assets/Lua/Core/
function Class(classname, super) --如何创建类
    --将参数的类型编码为一个字符串返回。
    -- 函数可能的返回值有 "nil" (一个字符串,而不是 nil 值), 
    --"number""string""boolean""table""function""thread""userdata"。 
    local superType = type(super)
    local cls

    print(tostring(superType))

    if superType ~= "function" and superType ~="table" then
        superType = nil
        super = nil
    end

    if super then
        cls = {}
        setmetatable(cls,{__index = super })    --设置元表
        cls.super = super
    else
        cls = { ctor = function() end}
    end

    cls.__cname = classname
    cls.__index = cls

    function cls.new(...)
        local instance = setmetatable({},cls)
        instance.class = cls
        instance.ctor(instance,...)
        return instance
    end

    return cls
end

使用如下

local UIManager = Class("UIManager")

可以继承同一个lua脚本,如其他界面脚本都继承UIBase脚本

local LaunchView = Class ('LaunchView', UIBase)

return LaunchView

 

posted @ 2021-10-20 17:27  搬砖独行者  阅读(210)  评论(0)    收藏  举报