lua面向对象封装

lua面向对象的一个封装,直接贴代码

--swfclass = {};
local cs = {};
function _class( child, base, ... )
--    _.s( child );
    if( cs[ child ] ) then error( "duplicate class : " .. child ) end;
    local c = _G[child];
    table.copy( c, base or {} );
    for ii = 1, select("#", ...) do
        table.copy( c, select(ii, ...) )
    end
    if base then setmetatable( c, base ) end;
    c.__index = c;
    c._className = child;
    cs[ child ] = c;
--    swfclass[child] = c;
end

Object = {};
_class( "Object", nil );
function Object.new ( self )
    local instance = {};
    setmetatable( instance , self );
    instance._className = self._className;
    return instance;
end

function Object.instanceof ( self, class )
    if class == nil then return false end;
    local c = self;
    while c do
        if( c == class ) then return true end;
        c = getmetatable( c );
    end
    return false;
end

function Object.toString( self )
    return table.tostring( self );
end

再添加新类时,如下

NewClass={}

_class("NewClass", Object);

function NewClass.new(self)

  local instance=Object.new(self);

  ....

  return instance;

end

 

function NewClass.func1(self)

end

 

SubClass={};

_class("SubClass", NewClass);

function SubClass.new(self)

  local instance=NewClass.new(self);

  ....

  return instance;

end使用方法:

local newclass=NewClass:new();

local subclass=SubClass:new();

subclass:func1();

转载于:https://www.cnblogs.com/marcher/p/luaoo.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值