MaximusZhou的专栏

概述

一个类就是像是一个创建对象的模具,对于。这个原型相当于其他语言中的类。但是原型同时也是一种常规的对象,当其他的对象(看成是原型的实例)遇到一个未知的操作时,就会去原型中查找。因此,在Lua这种没有类的语言中,为了表示一个类,只需创建一个专用作其他对象的原型。类和原型都是一种组织对象间共享行为的方式。本文将在Lua中模拟类,相关的代码可以在我的github上直接运行。

实现

clsObject = {__ClassType = "class type"}function clsObject:Inherit(o)o = o or {}o.__ClassType = "class type"o.mt = { __index = o}setmetatable(o, {__index = self})return oendfunction clsObject:New(…)local o = {}setmetatable(o, self.mt)if o.__init__ theno:__init__(…)endreturn oendfunction clsObject:__init__()endfunction clsObject:Destroy()endfunction clsObject:GetType()return "BaseClass"end

上面,,不管在继承机制还是实例化的过程,都是使用了元表技术,这样做符合

function Super(TmpClass)return getmetatable(TmpClass).__indexendfunction IsSub(clsSub, clsAncestor)local Temp = clsSubwhile 1 dolocal mt = getmetatable(Temp)if mt thenTemp = mt.__indexif Temp == clsAncestor thenreturn trueendelsereturn falseendend end

可以按下面实例代码来使用这个类

clsParent = clsObject:Inherit()function clsParent:Foo()print("ParentFoo!")endlocal ParentObj = clsParent:New()ParentObj:Foo()clsSon = clsParent:Inherit()function clsSon:Foo()Super(clsSon).Foo(self)print("SonFoo")endlocal SonObj = clsSon:Inherit()SonObj:Foo()print(IsSub(clsSon, clsParent))print(IsSub(clsSon, clsObject))

参考资料

《Lua程序设计》(第二版)

同生天地间,为何我不能。

MaximusZhou的专栏

相关文章:

你感兴趣的文章:

标签云: