lua元表(2)

来源:互联网 发布:windows主题桌面 编辑:程序博客网 时间:2024/04/30 08:50

这里写图片描述

2.5 多态
setmetatable5.lua

  people ={age=18}function people:new()local p={}setmetatable(p,self) self.__index=self return pendfunction people:growup()  self.age=self.age+1  print(self.age)end  man=people:new()function man:growup()       self.age=self.age+1     print("the man’s age is :"..self.age)end--testperson=people:new()person:growup() person=man:new()person:growup()

运行结果:
多态

2.6 元表练习代码
(1)setmetatable.lua

t={}m={a="i",b="love",c="you"}--表{__index=m}作为表m的元表setmetatable(t,{__index=m})  for k,v in pairs(t) do   print(k,v)  end  print("@@@@@")  print(t.a,t.b,t.c)

运行结果:
这里写图片描述

(2)setmetatable2.lua

function add(t1,t2)   assert(#t1==#t2)  --#取表长   local len=#t1   for i=1,len do    t1[i]=t1[i]+t2[i]     end      return t1end--setmetatable返回被设置的表t1=setmetatable({1,2,3},{__add=add})t2=setmetatable({10,20,30},{__add=add})t1=t1+t2for i=1,#t1 do       print(t1[i]) end

运行结果:
这里写图片描述

小结:以上两个表通过重载元表的加法运算使得能够做加法运算。元表通过特定的方法(setmetatable)设置到某个对象上,从而影响对象的行为

原创粉丝点击