[ Home Page | AppleScript | HyperCard | Misc. ]

Ben's HyperTalk Snippets

Here are a number of HyperTalk examples that may prove useful. Suggestions, comments or improvements welcomed!

The material contained here is offered AS IS. I make NO REPRESENTATION OR WARRANTY, express or implied, nor does any other contributor to this site. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE EXPRESSLY DISCLAIMED. Consequential and incidental damages are expressly excluded. Your actual damages are limited in any event to the price charged for this material.


Better Sums

HyperCard's 'sum' command is good at summing lists of comma-delimited numbers (i.e. sum (1,2,3)), but unable to sum numbers that are separated by other delimiters (i.e sum("1" & tab & "2" & tab &"3")). Here's a more generic version that uses the itemDelimiter property to let you specify how your number list is separated:

function delimitedSum theList, listDelimiter
  put the itemDelimiter into storedDelim -- save itemDelimiter for restore
  if listDelim is empty then put comma into listDelimiter -- like 'sum'
  else set the itemDelimiter to char 1 of value(listDelimiter) -- UNlike 'sum'
  put 0 into sumOfItems
  repeat with i = 1 to number of items in theList
    add value(item i of theList) to sumOfItems -- try to convert to a number
  end repeat
  set the itemDelimiter to storedDelim -- restore itemDelimiter
  return sumOfItems
end delimitedSum

on mouseUp -- some examples of using sumList
  answer delimitedSum("1,2,3") -- assumes comma separated numbers, like "sum"
  answer delimitedSum("1"&tab&"2"&tab&"3",tab) -- for number list separated by tabs
end mouseUp

Note that this custom function is about twenty times slower than the built-in 'sum' function so for user sanity it's probably best used for lists of less than 200 items... Also getting the value of each item slows it down by about half but is needed to ensure consistency with the normal 'sum' command because sum treats "two" as a number, not a string. Perhaps I'll turn it into a XFCN some day.


© Ben Lawson 1998. Feedback to benl@mac.com. Click here to return to my home page.