lua中使用table实现类和继承

Posted mttnor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lua中使用table实现类和继承相关的知识,希望对你有一定的参考价值。

--因为只有当读写不存在的域时,才会触发__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 ==> testB








以上是关于lua中使用table实现类和继承的主要内容,如果未能解决你的问题,请参考以下文章

(转载)笨木头Lua专栏基础补充20:面向对象——类和继承

Lua中使用table实现的其它5种数据结构

lua-table类的继承

Lua的面向对象

Lua的面向对象,封装,继承,多态

lua——元表元方法继承