Game Development Community

Array question

by Robert Lohaus · in Torque 2D Beginner · 11/22/2013 (1:06 am) · 4 replies

I am trying to simply create an array, that's it. The syntax guide is straight-forward:

$TestArray[n] (Single-dimension)

Of course you have to add the index:

$TestArray[10];

Doesn't work. Torsion gives me a compiling error and the program crashes if you push past the warnings.

The guide and the script is pretty straightforward, not sure what I am overlooking.

#1
11/22/2013 (3:54 am)
If your line of script really looks like this:
$TestArray[10];
Then, yes, you will get a parse error. TorqueScript does not require forward declaration of variables or arrays. So you need to assign it a type value to initialize it, even if it is nothing more than blank string.
$TestArray[10] = "";
#2
11/22/2013 (6:40 am)
I'd phrase it like this: "TorqueScript does not support forward declaration of variables or arrays." You can't just declare them, you must define them.

On the up side, TorqueScript arrays are technically zero-based index, but in practice you can start at any spot - they're very like a Lua array in this respect. The down-side is that I've never done any profiling and the system might just fill up "unused" indices with empty entries in a vector-like construct on the engine side.

To illustrate:
$TestArray[3] = "Three";  // start at 3
$TestArray[23] = "Twenty Three";  // define 23 without using any intervening slots

<edit>
Thinking about this just now I realized that when you save a TorqueScript array it converts the name[subscript] to namesubscript.

%object = new SimSet();
%object.TestArray[8] = "More Testing";
// becomes this in TAML
<SimSet 
    TestArray8 = "More Testing"
/>
So I think each array "slot" is treated as a separate individual variable and the whole "array" thing is just syntactic sugar - works for me....
#3
11/22/2013 (8:30 am)
Don't have to worry about unused indices filling up memory in TorqueScript because it doesn't actually implement real arrays:
// These variables
$TestArray[23] = 1;
$TestArray[2,3] = 2;
$TestArray[2,3,4] = 3;

// Are the same variables as below
$TestArray23 == 1; // true
$TestArray2_3 == 2; // true
$TestArray2_3_4 == 3; // true
#4
11/22/2013 (2:18 pm)
Thanks for the assistance, it was getting late last night.