Lua中实现面向对象的一种漂亮解决方案
在pil中,lua的作者推荐了一种方案来实现OO,比较简洁,但是我依然觉得有些繁琐。
这里给出一种更漂亮一点的解决方案,见下文:
这里提供Lua中实现OO的一种方案:
local_class={}
functionclass(super)
localclass_type={}
class_type.ctor=false
class_type.super=super
class_type.new=function(...)
localobj={}
do
localcreate
create=function(c,...)
ifc.superthen
create(c.super,...)
end
ifc.ctorthen
c.ctor(obj,...)
end
end
create(class_type,...)
end
setmetatable(obj,{__index=_class[class_type]})
returnobj
end
localvtbl={}
_class[class_type]=vtbl
setmetatable(class_type,{__newindex=
function(t,k,v)
vtbl[k]=v
end
})
ifsuperthen
setmetatable(vtbl,{__index=
function(t,k)
localret=_class[super][k]
vtbl[k]=ret
returnret
end
})
end
returnclass_type
end
现在,我们来看看怎么使用:
base_type=class() --定义一个基类base_type
functionbase_type:ctor(x) --定义base_type的构造函数
print("base_typector")
self.x=x
end
functionbase_type:print_x() --定义一个成员函数base_type:print_x
print(self.x)
end
functionbase_type:hello() --定义另一个成员函数base_type:hello
print("hellobase_type")
end
以上是基本的class定义的语法,完全兼容lua的编程习惯。我增加了一个叫做ctor的词,作为构造函数的名字。
下面看看怎样继承:
test=class(base_type) --定义一个类test继承于base_type
functiontest:ctor() --定义test的构造函数
print("testctor")
end
functiontest:hello() --重载base_type:hello为test:hello
print("hellotest")
end
现在可以试一下了:
a=test.new(1) --输出两行,base_typector和testctor。这个对象被正确的构造了。 a:print_x() --输出1,这个是基类base_type中的成员函数。 a:hello() --输出hellotest,这个函数被重载了。
在这个方案中,只定义了一个函数class(super),用这个函数,我们就可以方便的在lua中定义类:
base_type=class() --定义一个基类base_type
functionbase_type:ctor(x) --定义base_type的构造函数 print("base_typector") self.x=x end
functionbase_type:print_x() --定义一个成员函数base_type:print_x print(self.x) end
functionbase_type:hello() --定义另一个成员函数base_type:hello print("hellobase_type") end