Hey Everyone,
New to applescript with a question.
For the sake of education (in other words, this has no practical purpose yet), I would like to take a user input, say “Steve Jobs” – then get the total count of the words (2 not 10) and figure out whether or not the user inputed the first name first or last name first. ie.
Please write your first and last name:
|| Steve Jobs ||
get the count of words somehow to make sure he didn’t enter ||Steve Barney Jobs||
Then something like,
if firstword = steve then…
else if firstword - jobs then…
If you could help me out it would be much appreciated. Thank you.
repeat
set theNames to text returned of (display dialog "Please enter first and last name" default answer "" buttons {"Cancel", "Done"} default button "Done")
if (count words of theNames) is 2 then
set {firstName, lastName} to words of theNames
exit repeat
else
display dialog "Only two words, please!" & return & "Try it again." buttons {"OK"} default button 1 with icon 2
end if
end repeat
if firstName is "Steve" then
-- do something
end if
if lastName is "Jobs" then
-- do something
end if
There’s a subtlety in Stephan’s script worthy of explanation. Note that he has used a repeat loop with no limit set; He has not said: “repeat with anItem in aList” or “repeat until aTest is true or false” or “repeat while aTest is true or false”, or “repeat with k from 1 to 96 by 3”; he just said repeat, and then used a test to get out with an “exit repeat”.
This is a very good way of insisting that someone provide the answer you are looking for in a dialog asking for input. They can only answer correctly (with two words in this case) or they can click “Cancel” if you leave it there and exit the whole script.