Test if variable is defined.

Unlike other scripting languages I have used, Applescript does not have an isDefined() function. After much searching and struggling with this, I came up with a solution”pretty basic, but not immediately obvious to me.


	try
		someVar
	on error errmsg number num
		if num is -2753 then
			set someVar to "defaultValue"
		end if
	end try

I hope this is helpful to someone. I would welcome a more elegant solution if anybody has one. Unfortunately, I don’t have a way to use it as a function.

Hello.

I think the morale here is that you should always assign a value, even if that value is missing value , and test for that, or null if your prefer that one as “undefined”. You then may test for undefined.

An undefined value may arise, if a variable is assigned the result of a function, that has just the return statement, like so:


to undefine()
    return
end undefine
set a to undefine()

I think, this is more elegant:


try
	someVar
on error number -2753
	display notification "The variable     \"someVar\"     is not defined. 
Continue with setting to default value" sound name "Frog"
	set someVar to "defaultValue"
end try

display notification statement can be removed.