【步兵 lua】模拟继承 by EOS.
lua中的继承可能见过许多中了,比如cocos源码里的,是比较高级的。
但本文这种的写法,是适应我的习惯。 = 3=
class.lua
if new then return end
new = {}
class = function (clsName, super)
if(new[clsName])then error("!!! class ["..clsName.."] is Exist") end
local cls = nil
if super then
cls = {}
setmetatable(cls, super)
cls.super = super
else
cls = {}
end
cls.className = clsName
cls.__index = cls
new[clsName] = function(...)
local instance = setmetatable({}, cls)
instance:init(...)
return instance
end
return cls
end
BaseLayer.lua
if BaseLayer then return end
require "class"
BaseLayer = class("BaseLayer")
BaseLayer.fuck = 3
function BaseLayer:init()
self.x = 0
self.y = 0
self.width = 100
self.height = 150
end
function BaseLayer:show()
print "BaseLayer Show"
end
function BaseLayer:logProperty()
print("myClassName = "..self.className)
print("x:"..self.x)
print("y:"..self.y)
print("width:"..self.width)
print("height:"..self.height)
end
HelloLayer .lua
if HelloLayer then return end
require "class"
require "BaseLayer"
HelloLayer = class("HelloLayer", BaseLayer)
function HelloLayer:init(width, height)
self.super:init()
self.super.fuck = 2
if width and height then
self.width = width
self.height = height
end
end
main.lua
require "class"
require "HelloLayer"
function main()
--继承测试
local helloLayer = new.HelloLayer(200, 250)
helloLayer:show()
helloLayer:logProperty()
end
main()
输出
其他
至于if new then return end
之流,在文件中加入print之类的函数,
require多次,会多次执行,加上之后只会执行一次,应该会起到优化作用~
一天三连发,你怕不怕=。= , 累屎了,碎觉!!
See Again~
之前
真爱无价,欢迎打赏~