summaryrefslogtreecommitdiff
path: root/server/src/vm/library.lua
blob: 4545b1b5b287468c1045f8e44eda1a411dd21b54 (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
local createValue = require 'vm.value'
local createFunction = require 'vm.function'

local CHILD_CACHE = {}

local buildLibValue
local buildLibChild

function buildLibValue(lib)
    local tp = lib.type
    local value
    if     tp == 'table' then
        value = createValue('table')
    elseif tp == 'function' then
        value = createValue('function')
        local func = createFunction()
        value:setFunction(func)
        if lib.args then
            for _, arg in ipairs(lib.args) do
                func:createLibArg(arg)
            end
        end
        if lib.returns then
            for i, rtn in ipairs(lib.returns) do
                if rtn.type == '...' then
                    func:returnDots(i)
                else
                    func:setReturn(i, buildLibValue(rtn))
                end
            end
        end
    elseif tp == 'string' then
        value = createValue('string')
    elseif tp == 'boolean' then
        value = createValue('boolean')
    elseif tp == 'number' then
        value = createValue('number')
    elseif tp == 'integer' then
        value = createValue('integer')
    elseif tp == 'nil' then
        value = createValue('nil')
    else
        value = createValue(tp or 'any')
    end
    value:setLib(lib)

    if lib.child then
        for fName, fLib in pairs(lib.child) do
            local fValue = buildLibValue(fLib)
            value:rawSet(fName, fValue)
        end
    end

    return value
end

function buildLibChild(lib)
    if CHILD_CACHE[lib] then
        return CHILD_CACHE[lib]
    end
    local child = {}
    for fName, fLib in pairs(lib.child) do
        local fValue = buildLibValue(fLib)
        child[fName] = fValue
    end
    CHILD_CACHE[lib] = child
    return child
end

return {
    value = buildLibValue,
    child = buildLibChild,
}