Prev: Basic Arrays
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 constructed by prefixing each array element with a key and a colon (:). The key must be a string.
- A key in brackets ([]) directly indexes into the table and accesses the corresponding element.
- Using an index string for which no element exists is not an error, but returns the special value null. This is in contrast to indexing with numbers, where the corresponding element must exist.
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?"]
|
Next: Accessing SMS© 2004-2011 airbit AG, CH-8008 Zürich
Document AB-M-TUT-887