summaryrefslogtreecommitdiff
path: root/server/src/vm/multi.lua
blob: aaff97ecc3af49fa1e473e253af8e2ebe8687bac (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
73
74
75
76
77
local createValue = require 'vm.value'
local sourceMgr = require 'vm.source'

local mt = {}
mt.__index = mt
mt.type = 'multi'

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

function mt:get(index)
    for n = #self+1, index do
        self[n] = createValue('any', sourceMgr.dummy())
    end
    return self[index]
end

function mt:set(index, value)
    for n = #self+1, index-1 do
        self[n] = createValue('any', sourceMgr.dummy())
    end
    self[index] = value
end

function mt:first()
    local value = self[1]
    if not value then
        return createValue('nil', sourceMgr.dummy())
    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 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