l-set.lua /size: 1923 b    last modification: 2020-07-01 14:35
1if not modules then modules = { } end modules ['l-set'] = {
2    version   = 1.001,
3    comment   = "companion to luat-lib.mkiv",
4    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
5    copyright = "PRAGMA ADE / ConTeXt Development Team",
6    license   = "see context related readme files"
7}
8
9-- This will become obsolete when we have the bitset library embedded.
10
11set = set or { }
12
13local nums   = { }
14local tabs   = { }
15local concat = table.concat
16local next, type = next, type
17
18set.create = table.tohash
19
20function set.tonumber(t)
21    if next(t) then
22        local s = ""
23    --  we could save mem by sorting, but it slows down
24        for k, v in next, t do
25            if v then
26            --  why bother about the leading space
27                s = s .. " " .. k
28            end
29        end
30        local n = nums[s]
31        if not n then
32            n = #tabs + 1
33            tabs[n] = t
34            nums[s] = n
35        end
36        return n
37    else
38        return 0
39    end
40end
41
42function set.totable(n)
43    if n == 0 then
44        return { }
45    else
46        return tabs[n] or { }
47    end
48end
49
50function set.tolist(n)
51    if n == 0 or not tabs[n] then
52        return ""
53    else
54        local t, n = { }, 0
55        for k, v in next, tabs[n] do
56            if v then
57                n = n + 1
58                t[n] = k
59            end
60        end
61        return concat(t," ")
62    end
63end
64
65function set.contains(n,s)
66    if type(n) == "table" then
67        return n[s]
68    elseif n == 0 then
69        return false
70    else
71        local t = tabs[n]
72        return t and t[s]
73    end
74end
75
76--~ local c = set.create{'aap','noot','mies'}
77--~ local s = set.tonumber(c)
78--~ local t = set.totable(s)
79--~ print(t['aap'])
80--~ local c = set.create{'zus','wim','jet'}
81--~ local s = set.tonumber(c)
82--~ local t = set.totable(s)
83--~ print(t['aap'])
84--~ print(t['jet'])
85--~ print(set.contains(t,'jet'))
86--~ print(set.contains(t,'aap'))
87
88