以下代码来自Loxodon Framework,截取自其中的一段
function class(classname, super)local cls = {}cls.__classname = classnamecls.__class = clscls.base = function (self)return cls.superendcls.__type = 0cls.super = supercls.__index = clsif super thensetmetatable(cls,{__index = super, __call = function (t,...)local instance = setmetatable({},t) instance:ctor(...)return instanceend})elsecls.ctor = function (...)endsetmetatable(cls,{__call = function (t,...)local instance = setmetatable({},t)instance:ctor(...)return instanceend})endif not cls.ctor thencls.ctor = function (...) --构造函数endendreturn cls
end
调用方式
local t = {1,2,3}
t.age = 10local a = class("a",t)
print(a.age) --输出10local b = a() --调用了__call元方法,相当于是构造函数
print(b.age) --输出10
当调用a.age时,a相当于cls,会从__index中寻找age,即super,也就是t中寻找
而当通过local b = a() 的方式调用时,会进入到__call元方法中,instance 会从cls继承,相当于把cls设置为了instance的元表,最终返回instance