Skip to content

Instantly share code, notes, and snippets.

@prafulliu
Created December 18, 2012 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prafulliu/4324758 to your computer and use it in GitHub Desktop.
Save prafulliu/4324758 to your computer and use it in GitHub Desktop.
A lua metatable demo.
Set = {}
-- create a new set with the values of the
-- given list
local mt = {}
function Set.new(l)
local set = {}
setmetatable(set, mt)
for _, v in ipairs(l) do set[v] = true end
return set
end
function Set.union( a, b )
if getmetatable(a) ~= mt or getmetatable(b) ~= mt then
error("attempt to 'add' a set with a non-set value", 2)
end
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 l = {}
for e in pairs(set) do
l[#l + 1] = e
end
return "{" .. table.concat( l, ", ") .. "}"
end
function Set.print ( s )
print(Set.tostring(s))
end
mt.__add = Set.union
mt.__mul = Set.intersection
mt.__le = function ( a, b ) -- set containment
for k in pairs(a) do
if not b[k] then return false end
end
return true
end
mt.__lt = function ( a, b )
return a <= b and not (b <= a)
end
mt.__eq = function ( a, b )
return a <=b and b <= a
end
s1 = Set.new{10, 20, 30, 50}
s2 = Set.new{30, 1}
print(getmetatable(s1))
print(getmetatable(s2))
s3 = s1 + s2
Set.print(s3)
Set.print((s1+s2)*s1)
s4 = Set.new{2, 4}
s5 = Set.new{4, 10, 2}
print(s4 <= s5)
print(s4 < s5)
print(s4 >= s4)
print(s4 > s4)
print(s4 == s5*s4)
s = {1, 2, 3, 4}
t = {1, 2, 3}
for k, v in pairs(s) do
print (t[k])
if t[k] then
print "yes"
else
print "no"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment