1. 程式人生 > >lua實現類與繼承,多繼承

lua實現類與繼承,多繼承

--採用閉包方式實現類的概念--
--eg: 建立一個 Person類
local function Person()
	local tab = {
		high = 0,
		wight = 0,
			
	}

	function tab:PerMessage()
		print(self.high,self.wight);
	end

	return function()
		return tab;
	end
end

function createPerson(high,wight)
	
	local func_itor = Person();
	local per_obj = func_itor();
	per_obj.high = high;
	per_obj.wight = wight;

	return per_obj;
end

local per1 =createPerson(100,200);
local per2 =createPerson(111,2323);
local per3 =createPerson(32,33);
print(type(per1));
per1:PerMessage();
per2:PerMessage();
per3:PerMessage();
--********************************************************************************

--採用元表的方式實現類的概念
--定義一個Son 類
local Son = {};
Son.father = "";
Son.age = 0;

function Son:setSonMessage(m_father,m_age)
	self.father = m_father;
	self.age    = m_age;
end

function Son:SonMessage()
	print(self.father,self.age);
end

function createSon(Son_father,Son_age)
	local son_obj = {};
	setmetatable(son_obj,{__index = Son});
	son_obj:setSonMessage(Son_father,Son_age);

	return son_obj;
end

local son1 = createSon("張三",4);
local son2 = createSon("李四",2);
local son3 = createSon("王五",10);

son3:SonMessage();
son2:SonMessage();
son1:SonMessage();

--********************************************************************************

--lua 實現繼承的概念   
--[[*****************--
	繼承與多繼承就是讓__index能遍歷多個 表 找出正確表對應的元素

--*****************--]]
local function super(key,list)
	for i,v in ipairs(list) do
		local table = list[i];
		local var = table[key]
		if var then
			return var;
		end
	end
	return nil;
end
local GrandSon = {};
GrandSon.mess = "I have mess jiu zou le a mian dui nimen de kuang" 

function createGrandSon()
	local grandson_obj = {};
	local baseClass = {GrandSon,Son};--要繼承的類
	setmetatable(grandson_obj,{__index = function(t,k)--function(t,k)為lua直譯器機制-當__index指向的是函式時,預設有兩個引數,第一個為table,第二個為要查詢的key
		return super(k,baseClass);
	end});
	return grandson_obj;
end

local SS_1 = createGrandSon();
SS_1:setSonMessage("SSSDIOW",12)
SS_1:SonMessage();
print(SS_1.mess);