首页 > 代码库 > lua 元表

lua 元表

Set = {}Set.mt = {}function Set.new(t)    local set = {}    setmetatable(set, Set.mt)    for _, l in ipairs(t) do set[l] = true end    return setendfunction 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 resendfunction Set.tostring (set)    local s = "{"    local sep = ""    for e in pairs(set) do        s = s .. sep .. e        sep = ", "    end    return s .. "}"endfunction Set.print (s)    print(Set.tostring(s))ends1 = Set.new{10, 20, 30, 50}s2 = Set.new{30, 1}print(getmetatable(s1))print(getmetatable(s2))Set.mt.__add = Set.unions3 = s1 + s2Set.print(s3)

 

lua 元表