Testing for Missing Value in AppleScript

October 14, 2009

Here’s a quick one for the folks who are learning AppleScript out there…

The other day I got temporarily stuck on an AppleScript I’ve been tinkering with because I could not figure out how to test for what I perceived as a “null” value.  I had set a variable to a property of a class and was getting the result “missing value”.

Here’s some example code that illustrates it:

tell application "Finder" to set this_variable to the size of the desktop

The result is:

missing value

At first, I didn’t anything of it.  I told myself, “Easy.  Just figure out how to test for a null value and keep moving.”  Then I stopped to think about it.  As far as I knew there was no isNull() or similar function in AppleScript.  I quickly checked my trusty AppleScript 1-2-3 book and couldn’t find anything about testing for null values.

So my next thought was, “OK.  This is just about you learning how to think in AppleScript.  What is the AppleScript way to do this?”  A couple seconds later, I was convinced I had it.  Using the example above, my next line was equivalent to:

if (this_variable is equal to "") then
	display dialog "it worked"
end if

Nope.  I thought I may have gotten the syntax wrong, so I played around with that for awhile, but it didn’t work.

Of course if you Google something long enough, you will probably find the answer, and I found it, but it did take a little more time than I expected.  The solution was not only right in front of me but is ridiculously simple.

This statement does exactly what I was trying to accomplish.

if (this_variable is missing value) then
	display dialog "it worked"
end if

In AppleScript, “missing value” is an AppleScript constant and you can test for it.  Doh!  My brain got tracked in on “testing for null”, and I didn’t even consider that “missing value” was more than just an error message.  Bingo.  Lesson learned.

I know this is simple stuff, but these are the little stumbling blocks I am plowing through right now.  Hopefully this post will help another AppleScript newbie out there.

  • cvillepete
    Thanks! Awesome tip for newbies :)
  • shojo
    thanks a lot. i was fighting on this one
  • Thanks!
  • No problem. Happy to help!
blog comments powered by Disqus

Previous post:

Next post: