lua实现类与继承,多继承

来源:互联网 发布:合并后数组的中位数 编辑:程序博客网 时间:2024/05/06 11:54
--采用闭包方式实现类的概念----eg: 创建一个 Person类local function Person()local tab = {high = 0,wight = 0,}function tab:PerMessage()print(self.high,self.wight);endreturn function()return tab;endendfunction createPerson(high,wight)local func_itor = Person();local per_obj = func_itor();per_obj.high = high;per_obj.wight = wight;return per_obj;endlocal 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;endfunction Son:SonMessage()print(self.father,self.age);endfunction createSon(Son_father,Son_age)local son_obj = {};setmetatable(son_obj,{__index = Son});son_obj:setSonMessage(Son_father,Son_age);return son_obj;endlocal 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) dolocal table = list[i];local var = table[key]if var thenreturn var;endendreturn nil;endlocal 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,第二个为要查找的keyreturn super(k,baseClass);end});return grandson_obj;endlocal SS_1 = createGrandSon();SS_1:setSonMessage("SSSDIOW",12)SS_1:SonMessage();print(SS_1.mess);

0 0
原创粉丝点击