1 /**
2  * This module implements how arrays are internally handled. There is no reason to use this instead of constructing a
3  * ScriptAny with a D array.
4  */
5 module mildew.types.array;
6 
7 import mildew.types.object: ScriptObject;
8 
9 /**
10  * Implements arrays of ScriptAny values
11  */
12 class ScriptArray : ScriptObject
13 {
14     import mildew.types.any: ScriptAny;
15     import mildew.interpreter: Interpreter;
16 public:
17 
18     /**
19      * Takes a D array of ScriptAnys
20      */
21     this(ScriptAny[] values)
22     {
23         import mildew.types.bindings: getArrayPrototype;
24         super("array", getArrayPrototype, null);
25         _array = values;
26     }
27 
28     /**
29      * Returns the length of the array
30      */
31     size_t length() const { return _array.length; }
32 
33     /**
34      * This override allows for the length field
35      */
36     override ScriptAny lookupField(in string name)
37     {
38         if(name == "length")
39             return ScriptAny(_array.length);
40         else
41             return super.lookupField(name);
42     }
43 
44     /**
45      * This override allows for the length to be reassigned
46      */
47     override ScriptAny assignField(in string name, ScriptAny value)
48     {
49         if(name == "length")
50             return ScriptAny(_array.length = value.toValue!size_t);
51         else
52             return super.assignField(name, value);
53     }
54 
55     /**
56      * Returns a string representation of the array, which is [] surrounding a comma separated
57      * list of elements.
58      */
59     override string toString() const 
60     {
61         auto str = "[";
62         for(size_t i = 0; i < _array.length; ++i)
63         {
64             str ~= _array[i].toString();
65             if(i < _array.length - 1) // @suppress(dscanner.suspicious.length_subtraction)
66                 str ~= ", ";
67         }
68         str ~= "]";
69         return str;
70     }
71 
72     /// The actual array
73     ref ScriptAny[] array() { return _array; }
74     /// ditto
75     ref ScriptAny[] array(ScriptAny[] ar) { return _array = ar; } 
76 
77 private:
78 
79     ScriptAny[] _array;
80 }
81