Metatables and metamethods
- Metatables are similar to operator overloading in C++
- Metatables can be assigned to Tables
- Using setmetatable(theTable, theMetatable)
- There is also a getmetatable(theTable) which gives the metatable reference
- Metatables contain function definitions which are called metamethods
- The metamethods can be used to manipulate tables
The set example is given below
- This is from Programming in Lua by Roberto Ierusalimschy
local mt = {} Set = {} function Set.new (l) -- 2nd version local set = {} setmetatable(set, mt) for _, v in ipairs(l) do set[v] = 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 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 local s1 = Set.new{10, 20, 30, 50} local s2 = Set.new{30, 1} print(getmetatable(s1)) print(getmetatable(s2)) mt.__add = Set.union mt.__mul = Set.intersection --mt.__tostring = Set.tostring s3 = s1 + s2 Set.print(s3) Set.print((s1 + s2)*s1) print((s1 + s2)*s1)