欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Lua实现类继承

程序员文章站 2022-08-29 21:43:04
mulinherit.lua 复制代码 代码如下: --[[ author:looyer@sina.com date:2014/7/18 purpose:lua的...

mulinherit.lua

复制代码 代码如下:

--[[
author:looyer@sina.com
date:2014/7/18
purpose:lua的继承演示
--]]
--- base class "object"
local object = {_t = "object"}
function object:new(id)
    local o =
    {
        _id = id
    }
    setmetatable(o, self)
    self.__index = self
    return o
end
function object:type()
    return self._t
end
function object:id()
    return self._id
end
--- class "widget" driver from "object"
local widget = {_t = "widget"}
setmetatable(widget, object)
function widget:new(id)
    local o =
    {
        _id = id,
    }
    setmetatable(o, self)
    self.__index = self
    -- function (tb, key)
    --  return self[key]
    -- end
    return o
end
-- function widget:id()
--  return self._id
-- end
--- class "drawor" driver from "object"
local drawor = {_t = "drawor"}
setmetatable(drawor, object)
function drawor:new(id, name)
    local o =
    {
        _id = id,
        _name = name,
    }
    setmetatable(o, self)
    self.__index = self
    return o
end
function drawor:name()
    return self._name
end
--- class "drawplane" driver from "widget" and "drawor"
local drawplane = {_t = "drawplane", _father = {widget, drawor}}
function drawplane:new(id)
    local o =
    {
        _id = id,
    }
    setmetatable(o, self)
    self.__index =
    function (tb, key)
        if self[key] then return self[key] end
        for _, v in pairs(self._father) do
            if v._t == key then return v end
            if v[key] then return v[key] end
        end
    end
    return o
end
local vara = object:new()
local varb = widget:new(10)
local varc = drawor:new(30, "dwr")
local vard = drawplane:new(51)
print("vara type:", vara:type())
print("varb type:", varb:type())
print("varb._id: ", varb._id, varb:id())
print("varc name: ", varc:name())
print("vard type: ", vard:type())
print("vard id: ", vard:id())
print("vard father widget--", vard.widget:type())

以上就是本文所要分享的代码了,希望大家能够喜欢。