Associative Arrays

In the previous section, we solved the problem of looking up data which matches a given key in a table. Since this problem occurs very frequently in programming, m offers a standard solution for it: associative arrays, or arrays whose elements can be accessed directly with (string) keys. If we define our tiny database of keywords and replies in a single array as follows:

db=["party": "The party starts at 8pm!",
    "place": "I am at home.",
    "mood": "Just don't ask."];

we can access the elements directly by their keys:

print db["place"]
→ I am at home.
print db["mood"]
→ Just don't ask.
print db["hello"]
→ null

A few remarks:

An associative array is still a normal array and can also be indexed by numbers:

print len(db)
→ 3
print db[1]
→ I am at home

Array elements can also be modified via their keys, and new elements can be added by indexing with a new key:

db["place"]="I am at work.";
db["hello"]="How do you do?";
print len(db)
→ 4
print db
→ ["The party starts at 8pm!","I am at work.",
"Just don't ask.","How do you do?"]


© 2004-2010 airbit AG, CH-8008 Zürich
Document AB-M-TUT-869