lua多重继承

--多重继承
local function search(k,plist)
	for i=1,#plist do
		local v=plist[i][k] --   取一个基类
		if v then return v end
	end
end

function createClass(...)
	local c={};
	local parents={...};

	setmetatable(c,{__index=function(t,k) return search(k,parents) end } );

	c.__index=c;

	function c:new(o)
		o=o or {};
		setmetatable(o,c);
		return o;
	end

	return c;
end

Named={};
function Named:getname()
	return self.name;
end

function Named:setname(n)
	self.name=n;
end

Account={balance=100};

function Account:new(o)
	o= o or {}
	setmetatable(o,self);
	self.__index=self;
	return o;
end

function Account.deposit(self,v)
	self.balance=self.balance+v;
end

function Account:withdraw(v)
	if (v) > self.balance then error "insufficient funds"; end
	self.balance=self.balance-v;
end

NamedAccount=createClass(Account,Named);

user=NamedAccount:new{name="user admin"};
print (user:getname(),user.balance);

  

原文地址:https://www.cnblogs.com/byfei/p/2936925.html