Lua面向对象 实现 超详细注释 实现构造函数,析构函数,只读类模板等功能
源码
local _class = {}
function MakeTableReadOnly(Source)local proxy = {}local mt = {}mt.__index = Sourcemt.__newindex = function()print("ReadOnly!")endsetmetatable(proxy,mt)return proxy
end
function class(super)local class_type = {}class_type.ctor = falseclass_type.close = falseclass_type.super = superclass_type.new = function(...)local object = {}local createcreate = function(c,...)if c.super thencreate(c.super, ...)endif c.ctor thenc.ctor(object, ...)endendcreate(class_type,...)local mt = {}mt.__index = _class[class_type]local close_function = function(...)local destorydestory = function(c,...)if c.close thenc.close(object,...)endif c.super thendestory(c.super,...)endenddestory(class_type, ...)endmt.__gc = close_functionsetmetatable(object, mt)return objectendlocal vtbl = {}_class[class_type] = MakeTableReadOnly(vtbl)setmetatable(class_type, {__newindex = function(t,k,v)rawset(vtbl,k,v)end})if super thensetmetatable(vtbl, {__index = function(t,k)local res = _class[super][k]return resend})endreturn class_type
end
Base = class()
function Base:ctor(x)print("Base:ctor")self.x = x
end
function Base:close(x)print("Base:close")
end
function Base:Hello()print("Base:Hello")
end
SubBase = class(Base)
function SubBase:ctor(x,y)print("SubBase:ctor")self.y = y
end
function SubBase:close(x)print("SubBase:close")
end
function SubBase:Hello()print("SubBase:Hello")
end
function SubBase:SubHello()print(self.x)print(self.y)
end
Test = Base.new(1)
Test2 = SubBase.new(1,2)Test:Hello()
Test2:Hello()
Test2:SubHello()
getmetatable(Test2)["__index"].Hello = function()print("want to change!")
end
运行结果