Indices will be covered in much more depth and variety in the intermediate MUF programming chapter, but I think we should at least glance at them here.
A Muq object is conceptually just a little table of named values. You can store any values you like in an object, as many values as you like, and name them anything you like. That's really about all there is to say about a generic object! Except we should show you how to actually do it:
Stack: makeIndex --> o Stack: o Stack: <index _>
makeIndex
returns a brand-new index. In the above
example, we stick it in a global variable called o
and
then push it on the stack to see how MUF will display it.
Let's stick some named values on an index and then try
reading them back. MUF uses a path notation for doing
this which is much like the path notation used by unix: to
refer to the property o o
which is named chris
, we type
"o.chris":
Stack: makeIndex --> o Stack: "555-1423" --> o.kim "555-6261" --> o.pat Stack: o.kim Stack: "555-1423" pop o.pat Stack: "555-6261"
The above example suggests how we might use an index as a phone book, holding a set of names with corresponding phone numbers. Entering new phone numbers doesn't look too hard, nor looking them up.
What if we wanted to list all of the names and phone numbers on our list, however? We certainly don't want to have to remember all the names!
MUF provides a special type of loop just for iterating over the properties on an index:
Stack: o foreach name number do{ name , " " , number , "\n" , } kim 555-1423 pat 555-6261 Stack:
This loop takes an index as operand (o
in this case) and
executes the code between do{
and }
once for
each name.value pair on the index, with local variables
name
and number
set appropriately before each pass
through the code.
The variables' names are arbitrary, as usual:
Stack: o foreach key val do{ key , " " , val , "\n" , } kim 555-1423 pat 555-6261 Stack:
There is one final trick we need. Suppose we want to write a little function to look up a phone number given a name. It won't do to write
: phone-num -> name o.name ;
because MUF would take this as a request to look for someone named literally "name": We need some way to look up an arbitrary key we've been given on an index, not just a specific key we know ahead of time. The MUF syntax for doing that is:
: phone-num -> name o[name] ;
Stack: "robin" phone-num Stack: 555-1423 pop "pat" phone-num Stack: 555-6261
And that is really the essentials of programming with indices!
Go to the first, previous, next, last section, table of contents.