Variable scope problem - variable keeps resetting

I have an AppleScript Studio project which is being triggered by a hot key and needs to know which application the user was in when they pressed the hot key.

The triggering is working fine and I can get the apps name as a variable (which is declared as a property) but when I then try to use the variable it seems to be reverting to the property value which it was originally declared as.

Here’s my code:

property pFrontApp : ""
property debug_me : true


on hotkey_handler()
	tell application "System Events" to set pFrontApp to name of application processes whose frontmost is true
	set pFrontApp to pFrontApp as string
	if debug_me then log "HotKey: " & pFrontApp
	set the visible of window "QuickTag" to true
end hotkey_handler

on clicked theObject
	if the name of theObject is "HUDbtn" then
		if debug_me then log "Triggered from: " & pFrontApp
		if pFrontApp is equal to "Finder" then
			tell application "Finder" to repeat with MyItem in (get selection)
				set currentCom to (get comment of MyItem)
				set comment of MyItem to (currentCom & " " & "new tag") as string
			end repeat
			if debug_me then log "Triggered"
		else
			if debug_me then log "Problem"
		end if
	end if
end clicked

When I press the hot key in the Finder console shows the message:

Which is what I expect. However when I then click the HUDbtn in the QuickTag window console shows the following:

The pFrontApp variable has gone. Nothing is called that resets the variable I’ve tried using global variables and get the same problem. What am I overlooking? I’ve tried searching and cannot find a solution and have been playing around with the code for days and cannot spot what is wrong.

The on hotkey_handler() is called from a custom class.

I don’t know what the problem is but this looks unusual…

tell application "System Events" to set pFrontApp to name of application processes whose frontmost is true
set pFrontApp to pFrontApp as string

You might try this instead…

tell application "System Events" to set pFrontApp to name of (get first application process whose frontmost is true)

My guess would be that the way you are calling the hotkey_handler() is the problem. Without seeing more of the code I can’t offer an explicit solution. It seems that the way you are calling the hotkey_handler() that it’s a separate instance rather than the main instance that knows about the global variables. If you have this type of problem then a solution might be to write the pFrontApp variable to a plist file, and then in the custom class just read the plist file to get the value of that variable.

You are a star! I think it was a case of not seeing the wood for the trees. I was determined to use the variable directly and never even considered using a preference. It’s the first time I’ve called an applescript from a custom class so didn’t realise that might cause a problem.

Working fine now thanks.