[ Team LiB ] |
14.7 Unit ConversionsAppleScript provides a number of classes whose sole purpose is to allow you to perform measurement unit conversions. They are implemented as classes so that you can use the as operator to perform the conversion; that is, the conversion is really a coercion. Because of this implementation, the way you have to speak in order to perform a conversion ends up looking fairly silly. You can't say 3 feet; you have to coerce 3 (a number) to the feet class, by saying 3 as feet. Now you coerce to the desired class; suppose this is yards. But now you have a value of the yards class. You can't do anything with it, so you have to coerce it to a number. So, for example: on feetToYards(ft)
return ft as feet as yards as number
end feetToYards
feetToYards(3) -- 1.0
The implemented units are themselves a mixed lot. Many important units, such as acres and hectares, aren't implemented at all. Table 14-1 provides a list.
A much better list of conversion units is built into Mac OS X by way of the Unix tool units. Here's a way to use it: on convert(val, unit1, unit2)
set text item delimiters to " "
set conv to do shell script {"units", unit1, unit2} as string
return val * (word 1 of paragraph 1 of conv as real)
end convert
convert(4, "feet", "meters") -- 1.2192
|
[ Team LiB ] |