"if" in AppleScript

Discussion in 'Mac Programming' started by J. J., Sep 29, 2013.

  1. J. J. macrumors regular

    J. J.

    Joined:
    Oct 15, 2012
    Location:
    Italy
    #1
    Hi. This is part of the code of an AppleScript:

    Code:
    set filetypeword to choose from list {"1", "2", "3", "4", "5", "6", "7"} with prompt "XXXXX" with title "XXX" default items 1 without empty selection allowed
    if filetypeword is equal to "1" then
    	set filetype to "l"
    else if filetypeword is equal to "2" then
    	set filetype to "f"
    else if filetypeword is equal to "3" then
    	set filetype to "d"
    else if filetypeword is equal to "4" then
    	set filetype to "l -type f"
    else if filetypeword is equal to "5" then
    	set filetype to "l -type d"
    else if filetypeword is equal to "6" then
    	set filetype to "d -type f"
    else if filetypeword is equal to "7" then
    	set filetype to "l -type f -type d"
    end if
    do shell script "XXXXX" & filetype & "XXXXX"
    Once I run it I get error "Variable 'filetype' is not defined". Can you help me please? Is there another way to do this? Thank you.
     
  2. Red Menace macrumors 6502

    Joined:
    May 29, 2011
    Location:
    Littleton, Colorado, USA
    #2
    The result from choose from list is either a list (whether or not multiple selections are made or allowed), or the boolean false (if canceled).
     
  3. drsoong macrumors member

    Joined:
    Mar 24, 2008
    Location:
    Munich
    #3
    Scope of variables in Applescript?

    I have barely done anything with Applescript, but coming from a C++ background, I would have immediately said that by defining filetype within the if/elseif clauses, it is not scoped outside.

    Copy and pasting your code, I get the same error, defining filetype before-hand to some value on the first line it works for me.

    The Apple Developer page, though, seems to suggest that there is not a C++-like variable scope in Applescript.

    Code:
    set filetype to "-1"
    
    Maybe that helps.

    -drsoong
     
  4. Red Menace macrumors 6502

    Joined:
    May 29, 2011
    Location:
    Littleton, Colorado, USA
    #4
    AppleScript doesn't have the same scoping inside statement blocks. The main problem is the comparisons of a string to a list, which will fail, although if you define the variable beforehand it will act as a fall-through or default.

    The posted script is a bit redundant though, and can be shortened to something like:
    Code:
    set commandList to {"l", "f", "d", "l -type f", "l -type d", "d -type f", "l -type f -type d"}
    set filetypeword to (choose from list commandList with prompt "XXXXX" with title "XXX" default items {"l"} without empty selection allowed) as text
    if filetypeword is not "false" then do shell script "echo " & filetypeword -- or whatever
    
     

Share This Page