Programming

If you also find yourself making use of more programming languages and software technologies than you care to count, then you probably also forget from time to time the syntax for doing things. This page will contain a growing number of examples for a quick reminder:

Iterating through maps (tables/hash tables/dictionaries/associative arrays)

Lua

Lua doesn’t distinguish (at least not externally) between dictionaries and arrays

local hash={ 1, 'two', three=3, ['& four']='quatro' }
for i=1,4 do print( hash[i] ) end
print('n')
for k,v in pairs(hash) do print(k,v) end
1
two
nil
nil

1       1
2       two
three   3
& four  quatro

Python

hash={ 1:1, 2:'two', 'three':3, '& four':'quatro' }

for i in range(0,4):
     if i in hash:
         print(hash[i])
     else:
         print("no key")
         
print("")
      
for i in hash:
    print("%st%s" % (i,hash[i]))
no key
1
two
no key

1	1
2	two
& four	quatro
three	3

JavaScript

var hash={ 1:1, 2:'two', 'three':3, '& four':'quatro' }
for (var i=0; i<4; i++) 
    if (i in hash) console.log(hash[i]);
else
    console.log("no key");

console.log('')

for (i in hash)
    console.log( i+"t"+hash[i] )
no key
1
two
key

1	1
2	two
three	3
& four	quatro

PHP

<?php
$hash = array( 1=>1, 2=>'two', 'three'=>3, 'four'=>'quatro' );
for ($i=0; $i<4; $i++) 
    if (isset($hash[$i]))
         print("$hash[$i]n");
    else
         print("no keyn");

print("n");

foreach ( $hash as $key => $value )
    printf( "$keyt$valuen" );
?>
no key
1
two
no key

1       1
2       two
three   3
four    quatro

Perl

my %hash = ( 1=>1, 2=>'two', 'three'=>3, 'four key'=>'quatro' );
for ($i=0; $i<4; $i++) {
        if (exists $hash{$i}) {
                print("$hash{$i}n");
        }
        else {
                print("no keyn");
        }
}

print("n");

while ( ($key, $value) = each %hash ) {
        print("$keyt$hash{$key}n");
}
no key
1
two
no key

2       two
1       1
three   3
four    quatro

Leave a Reply

Your email address will not be published. Required fields are marked *