天天看點

XLua架構搭建——lua oop類設計

面向對象程式設計是目前比較主流的做法,在lua中并沒有類的概念,隻有table,通過table的特性,我們可以自己構造一個類。

關于這方面的資料比較多,就不在說明,不清楚的可以直接百度,這裡提供一個雲風大神的連接配接

在 Lua 中實作面向對象

下面提供一個類的實作,僅供參考,不知道哪裡來的了

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 == ) 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
            cls.ctor = function() end
        end

        cls.__cname = classname
        cls.__ctype = 

        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 = {}
            setmetatable(cls, {__index = super})
            cls.super = super
        else
            cls = {ctor = function() end}
        end

        cls.__cname = classname
        cls.__ctype =  -- lua
        cls.__index = cls

        function cls.new(...)
            local instance = setmetatable({}, cls)
            instance.class = cls
            instance:ctor(...)
            return instance
        end
    end
    --TODO:2015 8 10 
    if app~=nil then
        app.classDic[cls.__cname]=cls
    end
    return cls
end
           

繼續閱讀