Re: how to use data from choose from list
Re: how to use data from choose from list
- Subject: Re: how to use data from choose from list
- From: has <email@hidden>
- Date: Mon, 8 Jul 2002 21:21:25 +0100
RGould wrote:
>
This has got to be a no-brainer for someone one this list - - - can someone
>
tell me what I'm doing wrong in my "if" statement. I just want to be able
>
to branch, based on the results of the user clicking in a list. Right now,
>
selecting Apple does nothing.
>
>
>
set theList to {"Apple", "Orange", "Grape"}
>
>
set userChoice to choose from list theList
>
>
display dialog "userChoice = " & userChoice
>
>
if userChoice is "Apple" then
>
display dialog "Apple was selected."
>
end if
This gotcha gets everyone at some point. When comparing two values via the
'=' operator (a.k.a. 'is', 'is equal to'), AppleScript is very precise
about what constitutes equivalency - the classes of the two values are also
considered [1]. Run the following and see what value is returned:
set theList to {"Apple", "Orange", "Grape"}
set userChoice to choose from list theList
return userChoice
Notice that the value returned by 'choose from list' is a list, not a
string. e.g. If you try to perform the comparison:
{"Apple"} is "Apple"
the result is false. In many circumstances, AS will automatically coerce a
given value to a different class if it feels it will help, but not with
'='. This is usually helpful, but can sometimes lead to a false sense of
security (in other words: it pays to be aware of what's going on even if
it's AS that's doing it for you).
Two suggestions:
1. check how stuff like the '=' operator works by getting hold of a
suitable reference guide, e.g. the AppleScript Language Guide from Apple's
site]
2. write and test-run your script in small sections so you can see
firsthand exactly what's going on at each stage (e.g. as I've shown above).
This approach might seem a bit pedantic, but it's much more reliable than
banging out all the code first and then hoping it's all going to work when
you finally come to run it.
Anyway, to fix your code, simply modify the right-hand value so it's the
same class as the expected value:
if userChoice is {"Apple"} then
display dialog "Apple was selected."
end if
Or, if 'userChoice' is supposed to be a string anyway, perform a suitable
coercion at source:
set userChoice to (choose from list theList) as string
HTH
has
[1] Except (and there's always an exception somewhere, isn't there?) when
comparing an integer to a real.
--
http://www.barple.connectfree.co.uk/ -- The Little Page of Beta AppleScripts
_______________________________________________
applescript-users mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/applescript-users
Do not post admin requests to the list. They will be ignored.