aboutsummaryrefslogtreecommitdiff
path: root/src/lobject.js
blob: 4cc8c4e8ee4f5853d038d7f323b298ccb44f1bf4 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*jshint esversion: 6 */
"use strict";

const CT = require('./lua.js').constant_types;


class TValue {

    constructor(type, value) {
        this.type = type;
        this.value = value;
        this.metatable = null;
    }

}


class LClosure extends TValue {

    constructor(n) {
        super(CT.LUA_TLCL, null);

        this.p = null;
        this.nupvalues = n;
        this.upvals = [];

        this.value = this;
    }

}

class TString extends TValue {

    constructor(string) {
        super(CT.LUA_TSTRING, string);
    }

}


class Table extends TValue {

    constructor(array, hash) {
        super(CT.LUA_TTABLE, {
            array: array !== undefined ? array : [],
            hash: new Map(hash)
        });

        this.usermetatable = null;

        this.metatable = {
            __newindex: function (table, key) {
                if (key instanceof TValue) {
                    // Those lua values are used by value, tables and functions by reference
                    if ([CT.TNUMBER, CT.TSTRING, CT.TSHRSTR, CT.TLNGSTR, CT.TNUMFLT, CT.TNUMINT].indexOf(key.type) > -1) {
                        key = key.value;
                    }
                }

                if (typeof key === 'number') {
                    table.value.array[key] = value;
                } else {
                    table.value.hash.set(key, value);
                }
            },

            __index: function (table, key, value) {
                if (key instanceof TValue) {
                    // Those lua values are used by value, tables and functions by reference
                    if ([CT.TNUMBER, CT.TSTRING, CT.TSHRSTR, CT.TLNGSTR, CT.TNUMFLT, CT.TNUMINT].indexOf(key.type) > -1) {
                        key = key.value;
                    }
                }

                if (typeof key === 'number') {
                    return table.value.array[key];
                } else {
                    return table.value.hash.get(key);
                }
            },

            __len: function (table) {
                return t.value.array.length;
            }
        };
    }

}


module.exports = {
    LClosure: LClosure,
    TValue: TValue,
    Table: Table
};