Question about 'foreach'

cjswimmer

Member
I'd like to know how to use the Foreach construct in ASH.  I have a map declared at the beginning of one of my scripts:
Code:
string [string] CarColor;
that I add items to during the course of the script:
Code:
CarColor["Toyota"]="red";
CarColor["Ford"]="white";
CarColor["MBW"]="black";

at various points in my script I could have any number of items in this map, and I'm looking to create a function I can call to set all the items in the map to a specific value using something similar to the following:

Code:
void SetAllToBlue()
    { for each key in CarColor[] { CarColor[key] = "blue"; } }

Can someone please explain the syntax I would use?  Does a variable go where key would be and then I plug in the variable into the subsequent statement?  Are the empty brackets required when referencing the map in the foreach statement?
 

holatuwol

Developer
Taking your example, I wrote the following script which compiles a-okay, which should answer your questions.  Yes, you declare a new variable in the "key" section, and no, you do not need to add square brackets after the aggregate (if you want to specify a "slice" in a multi-dimensional map, then you can do so).  There were some other enhancements related to multi-dimensional maps and the "foreach" statement, but that's another story. :)

Code:
string [string] CarColor;
CarColor["Toyota"] = "red";
CarColor["Ford"] = "white";
CarColor["MBW"] = "black";

void setAllToBlue()
{
    foreach CarType in CarColor
        CarColor[CarType] = "blue";
}

setAllToBlue();

foreach CarType in CarColor
    print( CarType + " => " + CarColor[CarType] );
 
Top