算术运算的 Metamethods:
- Set={}
- function Set.union(a,b)
- local res=Set.new{}
- for k in pairs(a) do res[k]=true end
- for k in pairs(b) do res[k]=true end
- return res
- end
- function Set.intersection(a,b)
- local res=Set.new{}
- for k in pairs(a) do
- res[k]=b[k]
- end
- return res
- end
- function Set.tostring(set)
- local s="{"
- local sep=""
- for e in pairs(set) do
- s=s .. sep .. e
- sep=", "
- end
- return s .. "}"
- end
- function Set.print(s)
- print(Set.tostring(s))
- end
- Set.mt={}
- function Set.new(t)
- local set={}
- setmetatable(set,Set.mt)
- for _,l in ipairs(t) do set[l]=true end
- return set
- end
- s1=Set.new{10,20,30,50}
- s2=Set.new{30,1}
- print(getmetatable(s1))
- print(getmetatable(s2))
- Set.mt.__add = Set.union
- s3=s1+s2
- Set.print(s3)
- Set.mt.__mul = Set.intersection
- Set.print((s1+s2)*s1)
关系运算的 Metamethods:
- Set.mt={}
- function Set.new(t)
- local set={}
- setmetatable(set,Set.mt)
- for _,l in ipairs(t) do set[l]=true end
- return set
- end
- Set.mt.__add = Set.union
- Set.mt.__mul = Set.intersection
- Set.mt.__le = function (a,b)
- for k in pairs(a) do
- if not b[k] then return false end
- end
- return true
- end
- Set.mt.__lt = function (a,b)
- return a <= b and not (b <= a)
- end
- Set.mt.__eq = function (a,b)
- return a <= b and b <= a
- end
- s1=Set.new{2,4}
- s2=Set.new{4,10,2}
- print(s1<=s2)
- print(s1<s2)
- print(s1>=s1)
- print(s1>s1)
- print(s1==s2*s1)
库定义的 Metamethods:
- print({})
- Set.mt.__tostring = Set.tostring
- s1=Set.new{10,4,5}
- print(s1)
- Set.mt.__metatable = "not your business"
- s1 = Set.new{}
- print(getmetatable(s1))
表相关的 Metamethods:
The __index Metamethod:返回结果
- 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 = function (table, key)
- return Window.prototype[key]
- end
- w=Window.new{x=10,y=20}
- print(w.width)
The __newindex Metamethod:更新表
设置默认值:
- function setDefault(t,d)
- local mt={__index =function() return d end}
- setmetatable(t,mt)
- end
- tab={x=10,y=20}
- print(tab.x,tab.y,tab.z)
- print()
- setDefault(tab,0) --设置默认值
- print(tab.x,tab.y,tab.z)
监控表:
- t = {} --原始表
- local _t = t
- t = {} --代理
- local mt = { --表
- __index = function (t,k)
- print("*access to element " .. tostring(k))
- return _t[k] --原始表数据
- end,
- __newindex = function (t,k,v)
- print("*update of element " .. tostring(k) .. " to " .. tostring(v))
- _t[k] = v --更新后的数据
- end
- }
- setmetatable(t, mt)
- t[2]='hello'
- print(t[2])
只读表:
- function readOnly(t)
- local proxy={}
- local mt = { -- create metatable
- __index = t,
- __newindex = function (t,k,v)
- error("attempt to update a read-only table", 2)
- end
- }
- setmetatable(proxy,mt)
- return proxy
- end
- days=readOnly{"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
- print(days[1])
- --days[2]="Noday"