XCMD Sort
Volume Number: 4
Issue Number: 8
Column Tag: HyperChat™
XCMD Cookbook: Sorting Routines
By Donald Koscheka, Apple Computer, Inc.
In the last two issues we covered XCMD programming basics. First we looked at
the interface between Hypercard and XCMDs and then we discussed the callbacks and
how they can make your XCMD programming a little easier. This month, I present an
XCMD that adds a useful feature to Hypercard - the ability to sort lines in a text field.
This is a good example of XCMD programming since it extends Hypercard by
adding a new feature. In addition to adding features, XCMDs are a useful way of
speeding up some process that may have been written in HyperTalk. Sorting lines of
text is certainly something that could be accomplished in Hypertalk. But if you have a
lot of lines in the field, the Hypertalk script may be too slow. Enter the XCMD!
Before we can write the sort program, we must decide what it is we want to sort
and what form the data will be presented in. Let’s define a line as a string of text that
is spearated by a newline character. Next we’ll want to be able to sort both alphabetic
strings and numeric strings. We need the numeric sort because strings of characters
are sorted by ASCII value rather than numeric value.
Once we decide on the form and value of the data to sort, we can decide what we
need to pass to the XCMD from Hypercard. Obviously, we’ll need the lines. Parameter
1 will contain a handle to the field, parameter 2 will tell the XCMD whether to sort by
ASCII value (alphanumeric sort) or by numeric value (decimal sort). Parameter 3
tells the xcmd to sort in ascending or descending order. Actually LineSort only sorts in
ascending (smallest to largest) order. There really is no need to sort from largest to
smallest. You can simply report the lines “backwards” to get descending order. I’ve
left this as an exercise to the reader since it involves little more than reversing the
order of the FOR loop in two of the routines in SetNewText and SetNewNums.
When LineSort is complete, we’ll return the sorted list in the parameter block’s
returnValue. By making this an XFCN we can invoke it using the follwing format:
Put LineSort( card field “my list”, alpha ) into card field “my list”
The actual process of sorting can be broken down into the following steps:
(1) LineStart: Create an array of offsets into the list marking the start of each
line.