Javascript closures in AppleScript

There is another kind of closure in AppleScript, in which you ‘freeze’ a state of a free variable, when you access it from within a script object in AppleScript, I call that kind of closure for a ‘lisp closure’.

The great thing about a Javascript closure, is that it lets you have a global variable, ( or more like a static variable in C) that doesn’t interfere with anything else in the name space.

to Counter(seed)
	script
		property mv : seed
		to inc()
			set mv to mv + 1
			return mv
		end inc
	end script
end Counter

set m to Counter(4)
m's inc()
m's inc()
m's inc()
set k to Counter(4)
log k's inc()
# 5
log m's inc()
# 8

Hello.

This is an example of a ‘lisp closure’, as opposed to the javascript closure, I have never used a lisp closure for anything practical, but they may pop up unexpectedly now and then during debugging. :slight_smile:

The thing here, is that since x in the example below is a property declared at the top level, it is saved with the context of the script, when the script is assigned to a variable, so that there is no way you can change the value of x as seen from inside the script at the time the script was assigned to a variable.

Now, if we don’t assign the script to a variable, then the script will get that x has changed, if we run it at different stages.

This feature of saving the context, can also lead to a situatin where a script can’t run, because the address space is ‘used up’, by this ‘context saving’ (when run repeatedly).

property x : 5

script myscript
	display dialog x
end script

set x to 20

set dummy to myscript

set x to 10

run myscript -- ( or run dummy ) 
(* 20 *)

This example is stolen from the book “Applescript the Definitive guide” By Matt Neuburg.

Edit

Specified, that the ‘freezing’ only works for declared properties, and (not for globals for instance).