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)设置到某个对象上,从而影响对象的行为
阅读全文
0 0
- lua元表(2)
- Lua 元表(metatable)
- lua 元表(1)
- Lua-元表(Metatable)
- LUA元表、元操作
- Lua 元表 元方法
- Lua元表与元方法详解(转)
- LUA学习(七) 元表和元方法
- Lua语法小贴士(五)元表与元方法
- Lua元表和元方法(转载)
- Lua元表与元方法详解(转)
- Lua查找表(元表,_index)
- lua 元表
- lua元表学习
- lua元表
- lua元表
- lua元表
- lua元表学习
- Windows10 中的 Linux
- 数据库的操作
- 欢迎使用CSDN-markdown编辑器
- HTML5应用——欢乐老虎机
- 无题
- lua元表(2)
- JavaWeb中文乱码
- C语言 -- 宏的特殊用法和几个坑
- sql之储存过程与函数的区别
- 优雅的点
- LEFT JOIN左连接示例
- postgresql Linux 二进制文件安装
- 进入App判断网络状态(非广播实时监听)
- 2018网易校招编程题(8)小易喜欢的数列