I'm trying to write a script that runs both as an app and from the command line using osascript. In both cases, I want to pop up a "help" dialog in an appropriate way. In the case of the app, the dialog should pop up when I double click the app (the app's real work is all hapening in on open). In the case of the command-line launch, I want it to pop up when I run the script without arguments (eg: osascript myScript.scpt).
The attached script does not pop up the dialog properly when I double click the app, but it does work from the command line. If I delete just the argv on the first line, and then remove the -- on the second, thereby emulating the existence of argv, the dialog does pop up with the double click.
That is, the behavior is radically different when I use the supplied argv than it is when I don't. Is this a bug or am I doing something wrong?
on run argv -- if I remove the argv from this line
-- set argv to [] -- and then comment *in* this line, it works fine
getDefaults() -- when I double-click the app
if (count of argv) = 0 then
displayHelp() -- doesn't display on double click when I use "on run argv"
else
processFromCommandLine(argv)
end if
end run
on displayHelp()
display dialog "Help!"
end displayHelp
on processFromCommandLine(argv)
end processFromCommandLine
I solved the problem. When running as an app, argv doesn't exist, so attempting to access it aborts the app early with an excption toss. I solved the problem by wrapping the existing code in a try/on-error. Here's the working code:
on run argv
try
if not (count of argv) = 0 -- argv doesn't exist if a double-click launch so exception is thrown
processFromCommandLine(argv)
return
end if
on error -- you get here if app launched with a double click (argv won't exist)
end try
displayHelp() -- display on exception or if earlier if statment fails
end run
I could also have put the
displayHelp() in the "catch" block, but then I'd have had to also call it inside the try.