S2 Cookbook: Arrays

From Dreamwidth Notes
Revision as of 19:03, 10 August 2010 by Foxfirefey (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Access an item of an array or associative array

var string[] items = ["sock", "pants", "shirt", "skirt", "scarf"];
var string{} fruits = {"apple" => "red", "lemon" => "yellow", "grape" => "purple"};
 
## Accessing an array

# sock
print $items[0];
# pants
print $items[1];
 
## Accessing an associative array

# red
print $fruits{"apple"};
# yellow
print $fruits{"lemon"};
# purple
print $fruits{"grape"};

Cycle through all the items of an array or associative array

Please see the recipes:

Get the number of items in an array or associative array

Use the size keyword:

var string[] items = ["sock", "pants", "shirt", "skirt", "scarf"];
var int items_length = size $items;
 
var string{} fruits = {"apple" => "red", "lemon" => "yellow", "grape" => "purple"};
var int fruits_length = size $fruits;
 
# Items: 5; Fruits: 3
print "Items: $items_length; Fruits: $fruits_length";

Get the last item of an array

When you use a negative number as the index to an array, the count starts from the end of the array:

var string[] items = ["sock", "pants", "shirt", "skirt", "scarf"];
# scarf
print $items[-1];
# skirt
print $items[-2];

Get a random array item

Use the rand function to get an index within the array's range:

var string[] items = ["sock", "pants", "shirt", "skirt", "scarf"];
# goes from 0 to size-1 in indexing
var int random = rand(0, size $items - 1 );
var string pick = $items[$random];
print "Pick: $pick (item $random)";

You can even do it entirely inline:

var string pick = $items[rand(0, size $items - 1 )];

Reverse an array

Use the reverse keyword to reverse an array:

var string[] items = ["sock", "pants", "shirt", "skirt", "scarf"];
 
# scarf, skirt, shirt, pants, sock, 
foreach var string item ( reverse $items ) {
    print "$item, ";
}