Lua:元表(metatable)与元方法(meatmethod)
方法 lua
2023-09-14 09:06:31 时间
local _a1 = {20, 1, key1 = "hello", key2 = "world", lang = "lua"} local _a2 = {key1 = "hello",key2 = "world"} print("a2的metatable:",getmetatable(_a2)) setmetatable(_a2, {__index = _a1}) for _,v in pairs(_a2) do print(v) end print("a2的metatable:",getmetatable(_a2)) for k,v in pairs(getmetatable(_a2))do print(k,v) for i,j in pairs(v)do print(i,j) end end
a2的metatable: nil
hello
world
a2的metatable: table: 003CBB20
__index table: 003CAC60
1 20
2 1
key1 hello
lang lua
key2 world
--算术类元方法:字段:__add __mul __ sub __div __unm __mod __pow (__concat) --代码:(两个table相加) tA = {1, 3} tB = {5, 7} --tSum = tA + tB mt = {} mt.__add = function(t1, t2) for k, v in ipairs(t2) do table.insert(t1, v) end return t1 end setmetatable(tA, mt) tSum = tA + tB for k, v in pairs(tSum) do print(v) end
1
3
5
7
--关系类元方法: 字段:__eq __lt(<) __le(<=),其他Lua自动转换 a~=b --> not(a == b) a > b --> b < a a >= b --> b <= a 【注意NaN的情况】 --代码: mt = {} function mt.__lt(tA, tB) return #tA < #tB end tA, tB = {3}, {1, 2} setmetatable(tA, mt) setmetatable(tB, mt) print(tA < tB)
true
--用__index/__newindex来限制访问 function cannotModifyHp(object) local proxy = {} local mt = { __index = object, __newindex = function(t,k,v) if k ~= "hp" then object[k] = v end end } setmetatable(proxy,mt) return proxy end object = {hp = 10,age = 11} function object.sethp(self,newhp) self.hp = newhp end o = cannotModifyHp(object) o.hp = 100 print(o.hp) o:sethp(100) print(o.hp) object:sethp(100) print(o.hp)
10
10
100
Window = {} Window.prototype = {x = 0 ,y = 0 ,width = 100 ,height = 100,} Window.mt = {} function Window.new(o) setmetatable(o ,Window.mt) return o end Window.mt.__index = Window.prototype Window.mt.__newindex = function (table ,key ,value) if key == "wangbin" then rawset(table ,"wangbin" ,"yes,i am") end end w = Window.new{x = 10 ,y = 20} w.wangbin = "55" print(w.wangbin)
yes,i am
相关文章
- 30条MySQL查询的优化方法
- Lua获取系统时间和时间格式化方法及格式化参数
- (推荐)手机频率与信号测试软件Cellular-Z使用方法
- 【转】在COCOS2D-LUA中使用PROTOBUF(XCODE配置方法)
- EasyNVR无插件流媒体服务器前端技术防止重复提交的方法
- 分享我的面向对象分析方法
- 在OpenResty中使用lua-zlib的方法
- Atitit 局部图查找大图 方法 与 说明
- Atitit 记录方法调用参数上下文arguments
- atitit.api设计 方法 指南 手册 v2 q929.docx
- 基于JAVA实现的WEB端UI自动化 - WebDriver框架篇 - ant使用 - ant安装、环境变量配置、ant实例及运行Ant Build 出现问题的解决方法
- Lua 错误处理方法
- 【Android Gradle 插件】Module 目录下 build.gradle 配置文件 ( plugins 闭包代码块中引入插件 | PluginAware#apply 方法引入插件 )
- Win11系统提示backgroundtaskhost.exe系统错误解决方法
- Win11麦克风权限的开启方法
- Lua 判断表是否为空方法
- JAVA操作Excel表格:方法二:POI的使用②:Excel实战之POI解析读取excel文件(低版本)