S2 Cookbook: Arrays

From Dreamwidth Notes
Revision as of 01:57, 8 August 2010 by Foxfirefey (Talk | contribs)

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

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

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, ";
}