Lua的面向对象


项目中一直是使用functions 这个方法模拟面向对象,在cocos3.0 中提供的 functions.lua文件有定义 。
1、核心代码为:
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
            cls.ctor = function() end
        end

        cls.__cname = classname
        cls.__ctype = 1
		cls.__index = cls

	    
            
        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

function clone(object)
    local lookup_table = {}
    local function _copy(object)
        if type(object) ~= "table" then
            return object
        elseif lookup_table[object] then
            return lookup_table[object]
        end
        local new_table = {}
        lookup_table[object] = new_table
        for key,value in pairs(object) do
            new_table[_copy(key)] = _copy(value)
        end
        return setmetatable(new_table,getmetatable(object))
    end
    return _copy(object)
end
2、解释图



注意实例化继承自C++层类 和 lua类的区别

3、使用lua面向对象的注意事项

(1)lua层类的实例化是使用 instance = setmetatable( {},cls)来模拟的,所以需要注意的是如果类A中有属性 是一个table
属性,如果类A的实例a改变了其中的一个属性,那么其他所有的A的类的对象都会访问该属性都是被修改了的。


输出结果:


注意输出A类的实例对象 b时候 b.tab.id 已被改变 【这点理解了 lua 元表的 metatable 的 __index 不难理解,但是使用Lua的面向对象时候需要注意】



2、继承中调用构造函数需要助于的点,访问父类的够着函数时候用 类名访问,而不要使用 self



如果将 X.super 改成 self.super 那么在实例化C调用 self.init() 会出死是循环.
注意:
self 指向传入的对象. 使用 local c = C.new() c.init() 那么其实在 B A  中使用的 self 都是C 的对象 c 出现 c.init() --> b.init() ---> b.init() ---> 死循环 而在面向对象的中的 this 是指向当前对象,这个需要注意lua面向对象self 与this 区别。

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...