zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    [原创]利用Browser协议探测内网主机操作系统版本(无需端口无视防火墙)
    [EXP]Microsoft Windows 10 (Build 17134)
    [EXP]Microsoft Windows
    [EXP]Apache Spark
    [EXP]Adobe ColdFusion 2018
    [EXP]ThinkPHP 5.0.23/5.1.31
    [EXP]Cisco RV110W
    [EXP]Huawei Router HG532e
    [EXP]Microsoft Windows CONTACT
    [EXP]Microsoft Windows 10
  • 原文地址:https://www.cnblogs.com/mttnor/p/10345513.html
Copyright © 2011-2022 走看看