Arrays

The below works… But I don’t like it.

`local MyString = “Hello World”;
MyArray <- [1,2,3,4,5];

for (local n=0;n<5;n++){
MyArray[n] = MyString;
}

foreach(x in array){
server.log(x);
}`

Can this be written like you would in C? Sorry the below code could be very wrong… But it’s what I need in theory. I’m trying to read in data as a string and hold it in an array so I can iterate through it.

`
char MyArray[20][12];

int i;
for (i = 0; i < 20; ++i){
strcpy(MyArray[i], “Hello World”);
}
`

Thank you!

If I understand what you’re trying to do, the Squirrel code should look something like the following:

`function test() {
local MyArray = array(20);

local i = 0;
for(i = 0; i < 20; i++) {
    MyArray[i] = "Hello World";
}

for(i = 0; i < 20; i++) {
    server.log(MyArray[i]);
}   

}
test();`

It’s interesting to note that Squirrel arrays are treated as tables with integer indexes. This means we can do all sorts of interesting things, and can build a dynamically sized array if we want:

`function test();
// create an empty array
local MyArray = [];

local i = 0;
for(i = 0; i < 20; i++) {
    // push elements into the array
    MyArray.push("Hello World");
}

for(i = 0; i < 20; i++) {
    server.log(MyArray[i]);
}

}
test();`

As a side note: Here are a couple more ways to index through an array / table:
`foreach(key, value in MyArray) {
server.log(key + ": " + value);
}

foreach(key, value in MyArray) {
server.log(key + ": " + MyArray[key]);
}`

Hopefully that helps?

Fantastic!

local MyArray = array(20);

and…

local MyArray = [] MyArray.push

This is exactly what I was looking for thank you very much. Was scratching head for a while with index errors!

If you can stomach it, I encourage you to search through the Squirrel documentation! If you’re a C programmer, that page, plus the Squirrel stdlibs may be of use, and with some searching provide a lot of useful info!