1 扩展方法到两个文件
map = {}
extend = {}
setmetatable(extend, map)
function extend.fun1()
print("fun1")
end
extend.data = "xxx"
local function newFunc(t, k)
local ret = rawget(extend, k)
return ret
end
setmetatable(map, {__index = newFunc})
print(map.fun1()) --map.fun1 变成了extend fun1
print(map.data) --map.data 变成了 extend data
--打印结果
fun1
xxx
2 new 新的类
a = {}
function a.new(x)
t = {}
setmetatable(t, {__index = a})
t.x = x
return t
end
function a:outputdata()
print(self.x)
end
local c1 = a.new(4)
local c2 = a.new(10)
c1:outputdata()
c2:outputdata()
--输出结构
4
10
3 继承关系
function implement(handle, interface)
for key, value in pairs(interface) do
handle[key] = value
end
end
function def_class(classname, baseCls)
local cls = {}
if baseCls then
implement(cls, baseCls)
end
cls.__index = cls
cls.__classname = classname
function cls:new(...)
local o = {}
setmetatable(o, cls)
if o.ctor then
o:ctor(...)
end
return o
end
return cls
end