类的实现
lua中其实是没有类的,有的只是表(table),而类之间的继承也就是将父类的表连到了一起,派生类中没有找到的属性和方法就通过元表查找父类
function class(classname, ...)
local cls = {__cname = classname}
local supers = {...}
for _, super in ipairs(supers) do
local superType = type(super)
assert(superType == "nil" or superType == "table" or superType == "function",
string.format("class() - create class \"%s\" with invalid super class type \"%s\"",
classname, superType))
if superType == "function" then
assert(cls.__create == nil,
string.format("class() - create class \"%s\" with more than one creating function",
classname));
-- if super is function, set it to __create
cls.__create = super
elseif superType == "table" then
if super[".isclass"] then
-- super is native class
assert(cls.__create == nil,
string.format("class() - create class \"%s\" with more than one creating function or native class",
classname));
cls.__create = function() return super:create() end
else
-- super is pure lua class
cls.__supers = cls.__supers or {}
cls.__supers[#cls.__supers + 1] = super
if not cls.super then
-- set first super pure lua class as class.super
cls.super = super
end
end
else
error(string.format("class() - create class \"%s\" with invalid super type",
classname), 0)
end
end
cls.__index = cls
if not cls.__supers or #cls.__supers == 1 then
setmetatable(cls, {__index = cls.super})
else
setmetatable(cls, {__index = function(_, key)
local supers = cls.__supers
for i = 1, #supers do
local super = supers[i]
if super[key] then return super[key] end
end
end})
end
if not cls.ctor then
-- add default constructor
cls.ctor = function() end
end
cls.new = function(...)
local instance
if cls.__create then
instance = cls.__create(...)
else
instance = {}
end
setmetatableindex(instance, cls)
instance.class = cls
instance:ctor(...)
return instance
end
cls.create = function(_, ...)
return cls.new(...)
end
return cls
end
上面是cocos官方对class的实现
ctor是他的构造函数
可以用new或者create去实例化
类的运用
local dog = class("dog")
function dog:ctor ( ... )
print("构造函数")
end
function dog:eat( ... )
print("狗吃屎")
end
local dog1 = dog.new()
dog1:eat()
这里声明一个类dog,然后调用它的方法eat。
类的继承
local dog = class("dog")
function dog:ctor ( ... )
print("父类构造函数")
end
function dog:eat( ... )
print("狗吃屎")
end
local Huskie = class("Huskie",dog)
function Huskie:ctor( ... )
Huskie.super.ctor(self)
print("子类构造函数")
end
local huskie1 = Huskie.create()
huskie1:eat()
Huskie(哈士奇)继承dog,他也拥有dog的方法eat
注意继承父类的方法需要先调用super的相应的方法,第一个参数传self。
继承多个父类
--狗
local dog = class("dog")
function dog:ctor ( ... )
print("dog构造函数")
end
function dog:eat( ... )
print("狗吃屎")
end
--金毛
local GoldenRetriever = class("GoldenRetriever")
function GoldenRetriever:ctor( ... )
print("GoldenRetriever构造函数")
end
function GoldenRetriever:cry( ... )
print("金毛哭了")
end
--哈士奇
local Huskie = class("Huskie",dog,GoldenRetriever)
function Huskie:ctor( ... )
Huskie.super.ctor(self)
print("子类构造函数")
end
local huskie1 = Huskie.create()
huskie1:eat()
huskie1:cry()
lua中 “...” 表示全部参数
网友评论