Created
July 8, 2014 02:40
-
-
Save liuhuajin/eba463003296584924c6 to your computer and use it in GitHub Desktop.
metatable 操作 lua 13.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Set = {} | |
function Set.new(t) | |
local set = {} | |
setmetatable(set, Set.mt) | |
for _, l in ipairs(t) do set[l] = true end | |
return set | |
end | |
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 = {} | |
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment