~nch/gamelog

ref: 75432213d3972f26c03ef636da68ed482f0ac908 gamelog/set.lua -rw-r--r-- 1.9 KiB View raw
75432213 — nc refactoring debug code out a bit 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
local set = {}

-- TODO: define iterator for set.

function set.add(s, e)
    s[e] = true
end

function set.remove(s, e)
    s[e] = nil
end

function set.new(elements)
    local s = {}
    setmetatable(s, set.mt)
    for _, e in pairs(elements or {}) do s[e] = true end
    return s
end

setmetatable(set, {__call = function(_, ...) return set.new(...) end})

function set.union(a, b)
    local r = set.new()
    for k in pairs(a) do r[k] = true end
    for k in pairs(b) do r[k] = true end
    return r
end

function set.intersection(a, b)
    local r = set.new()
    for k in pairs(a) do
        r[k] = b[k]
    end
    return r
end

function set.totable(s)
    local r = {}
    for k, _ in pairs(s) do
        table.insert(r, k)
    end
    return r
end

set.mt = {}
set.mt.__add = set.union
set.mt.__sub = function(a, b)
    local r = set()
    for k in pairs(a) do
        if not b[k] then
            r[k] = true
        end
    end
    return r
end
set.mt.__mul = set.intersection
set.mt.__index = {add = set.add, remove = set.remove}
set.mt.__pairs = function(t)
    return function(t, k)
        local v
        k, v = next(t, k)
        if v then return k, k end
    end, t, nil
end
set.mt.__tostring = function(t)
    local keys = {}
    for k, _ in pairs(t) do
        table.insert(keys, tostring(k))
    end
    return '{' .. table.concat(keys, ', ') .. '}'
end

set.mt.__eq = function(a, b)
    return next(a - b) == nil and next(b - a) == nil
end

local function test_set()
    assert(is_eq(set.totable(set.new({1,2,3})), {1,2,3}))

    assert(#set.totable(set.new()) == 0)
    assert(#set.totable(set()) == 0)
    assert(#set.totable(set({1,2,3})) == 3)

    local x = set()
    x:add(1)
    x:add(2)
    x:add('b')
    local a = set.totable(x)
    assert(#a == 3)
    for _, e in pairs(a) do -- make sure the 'add' function doesn't crop up in iteration
        assert(e ~= add)
    end
end

return set