--由於只有當讀寫不存在的域時,纔會觸發__index和__newindex classA = {className = "classA",name="classAInst"} function classA:new(newobject) newobject = newobject or {} setmetatable(newobject, {__index = self})--當在newobject找不到key對應的value時,就到self(即classA)類中查找 return newobject end function inherit(p) local newclass = {className = "classB",parent = p} setmetatable(newclass,{__index=p})--當在newclass中找不到key對應的value時,就到p類中查找 function newclass:new(newobject) newobject = newobject or {} setmetatable(newobject,{__index = newclass})--當在newobject找不到key對應的value時,就到newclass類中查找 return newobject end return newclass end testA = classA:new() print("testA ==> ",testA.className) print("testA ==> ",testA.name) testB = inherit(classA):new({name = "testB"}) print("testB ==> ",testB.className) print("testB ==> ",testB.name) testC = inherit(classA):new() print("testC ==> ",testC.className) print("testC ==> ",testC.name) testD = inherit(testB):new() print("testD ==> ",testD.className) print("testD ==> ",testD.name)
testA ==> classA
testA ==> classAInst
testB ==> classB
testB ==> testB
testC ==> classB
testC ==> classAInst
testD ==> classB
testD ==> testBspa