--[[
实现类的用法
]]--
local _class={}
function class(super)
local class_type={}
class_type.ctor=false
class_type.super=super
class_type.new=function(...)
local obj={}
do
local create
create = function(c,...)
if c.super then
create(c.super,...)
end
if c.ctor then
c.ctor(obj,...)
end
end
create(class_type,...)
end
setmetatable(obj,{ __index=_class[class_type] })
return obj
end
local vtbl={}
_class[class_type]=vtbl
setmetatable(class_type,{__newindex=
function(t,k,v)
vtbl[k]=v
end
})
if super then
setmetatable(vtbl,{__index=
function(t,k)
local ret=_class[super][k]
vtbl[k]=ret
return ret
end
})
end
return class_type
end
--基类people
local people = class();
--构造函数
function people:ctor(sex,age)
print("people new .........");
self.sex = sex;
self.age = age;
end
--成员函数
function people:show()
print("people show .............");
print("sex: ",self.sex," age: ",self.age);
end
--成员函数
function people:speek()
print("people speek ...........");
end
--派生类boy 继承至 people
local boy = class(people);
function boy:ctor(sex,age,tag)
print("boy new .............");
self.tag = tag;
end
--派生类重写基类方法
function boy:show()
print("boy show ...................");
print("sex: ",self.sex," age: ",self.age," tag: ",self.tag);
end
-----------测试代码
--实例化类boy
peo1 = boy.new("Rain","25","1");
--调用自己重写的方法
peo1:show();
--调用基类方法
peo1:speek();
print("-------------------------")
peo2 = boy.new("second","10","2");
peo2:show();
peo2:speek();
print("-------------------------")
peo1:show();
peo1:speek();
print("***********************");
可以直接在lua编译器调试。