您的位置:首页 > 编程语言 > Lua

Lua面向对象实现

2016-05-31 20:46 417 查看
function baseClass(base)
local cls = {}
if base then
cls = {}
for k,v in pairs(base) do cls[k] = v end
cls.base = base
else
cls = {ctor = function() end}
end

--cls.__cname = classname
cls.__index = cls

function cls:new(...)
local instance = setmetatable({}, cls)
local create
create = function(c, ...)
if c.base then
create(c.base, ...)
end
if c.ctor then
c.ctor(instance, ...)
end
end
create(instance, ...)
--instance.class = cls
return instance
end
return cls
end

这个类主要是把基类和派生类绑定起来,并且调用ctor构造函数

用法如下

local base = baseClass()

function base:ctor()
end

function base:funcA()
end

function base:funcB(value)
end

local top = baseClass(base)

function top:ctor()
end

function top:funcB(value)
self.base.funcA(self, value)
end

注意调用父类的方法要用"."别用":"是因为baseClass实现问题,不能用语法糖了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: