summaryrefslogtreecommitdiff
path: root/server/src/vm/multi.lua
blob: 809b5244f914569007af0e7fe880804197074801 (plain)
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
local mt = {}
mt.__index = mt
mt.type = 'multi'
mt.len = 0

function mt:push(value, isLast)
    if value and value.type == 'list' then
        if isLast then
            for _, v in ipairs(value) do
                self.len = self.len + 1
                self[self.len] = v
            end
        else
            self.len = self.len + 1
            self[self.len] = value[1]
        end
    else
        self.len = self.len + 1
        self[self.len] = value
    end
end

function mt:get(index)
    return self[index]
end

function mt:set(index, value)
    self[index] = value
end

function mt:first()
    local value = self[1]
    if not value then
        return nil
    end
    if value.type == 'multi' then
        return value:first()
    else
        return value
    end
end

function mt:eachValue(callback)
    local i = 0
    for n, value in ipairs(self) do
        if value.type == 'multi' then
            if n == self.len then
                value:eachValue(function (_, nvalue)
                    i = i + 1
                    callback(i, nvalue)
                end)
            else
                i = i + 1
                value:first()
            end
        else
            i = i + 1
            callback(i, value)
        end
    end
end

function mt:merge(other)
    other:eachValue(function (_, value)
        self:push(value)
    end)
end

return function ()
    local self = setmetatable({}, mt)
    return self
end