10.2. Making a Simple AppleScript DatabaseAppleScript records can store just about any type of information you want. In the previous scripts, for example, you stored numbers and strings of text. But suppose you had the information from Table 10-1 and wanted to create a database from that.
Here's how you'd encode that information in AppleScript: set myChicken to {nickname:"Matthew", weightInPounds:20, ¬ heightInInches:26.5, rooster:true} set kfcChicken to {nickname:"Colonel", weightInPounds:15, ¬ heightInInches:22.3, rooster:true} set chickenLittle to {nickname:"Little", weightInPounds:3, ¬ heightInInches:10.9, rooster:false} set myDatabase to {myChicken, kfcChicken, chickenLittle} --Creates a database As you can see, a simple AppleScript database is no more than a list of individual records. (In fact, even when you work with commercial database programs, you'll find that they're really just clusters of records, too.) This script stores three separate kinds of data in myDatabase: strings for a chicken's nickname, numbers for a chicken's weightInPounds and heightInInches, and Boolean values (Sidebar 5.5) to specify whether the chick is a rooster. AppleScript keeps each type of information separate, so it won't get confused if you use three, four, or even more kinds of information in your database records. 10.2.1. Searching an AppleScript DatabaseFor most things in AppleScript, you can use the every keyword to narrow down a list of items to a few that match certain criteria (Section 6.3). Unfortunately, this neat trick doesn't work for finding records within an AppleScript database. To work around this limitation, you have to iterate (Section 6.4) through the database, checking each record individually to see if it matches your criteria. Obviously this is an annoying, slower way of searching, but it's unfortunately your only choice for AppleScript databases. Here, for example, is how you'd search through that chicken database to find the chickens that weigh more than 10 pounds: set myChicken to {nickname:"Matthew", weightInPounds:20, ¬ heightInInches:26.5, rooster:true} set kfcChicken to {nickname:"Colonel", weightInPounds:15, ¬ heightInInches:22.3, rooster:true} set chickenLittle to {nickname:"Little", weightInPounds:3, ¬ heightInInches:10.9, rooster:false} set myDatabase to {myChicken, kfcChicken, chickenLittle} --Part 1: set heavyChickens to {} --Part 2: repeat with currentRecord in myDatabase --Part 3: if the weightInPounds of currentRecord is greater than 10 then set heavyChickens to (heavyChickens & the nickname of currentRecord) end if end repeat --Part 4: choose from list heavyChickens with prompt ¬ "Chickens weighing more than 10 pounds:" Here's how the new code works:
Now that you know how to create, modify, and search databases, you can get down to real business: making databases out of useful information. |