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();