Loosely put,
closures take a blob of code and the bindings of some
variable names to variables and return a thing which can be executed
like the blob of code, but, while it's executing the code, the
name<->variable mappings saved in the closure are temporarily
reinstated.
In other words, "static local variables"?
In some respects. However, each closure contains its own distinct set
of values; most languages' "static local variables" don't work that
way.
As a really simple example, consider (to use Lisp as the language,
since that's what I'm most familiar with practical closures in; I'm
using my own Lisp here, which is pretty close to Zetalisp in the
relevant respects):
(defun make-adder (n) #'(lambda (x) (+ x n)))
Then
(setq a4 (make-adder 4))
(setq a10 (make-adder 10))
a4 and a10 are then closures. Each one has (lambda (x) (+ x n)) as its
code blob; its binding list includes a binding of n to some value - 4,
in the case of a4, or 10, in the case of a10.
(funcall a4 7) -> 11
(funcall a10 7) -> 17
Whereas, in C, which doesn't have closures but does have static local
variables,
static int n;
static int adder(int x) { return(x+n); }
static int (*make_adder(int val))(int)
{
n = val;
return(&adder);
}
the function returned by make_adder will always add the last value
passed to make_adder, regardless of which call's return value is
called. That is, after
int (*a4)(int);
int (*a10)(int);
a4 = make_adder(4);
a10 = make_adder(10);
Then (*a4)(7) gives 17, not 11 - though if called between the two
make_adder calls, it returns 11. This is because the returned pointers
are _not_ closures; the binding of the name n in adder to the storage
location it refers to is fixed, and all those references refer to the
same location. (Actually, I've seen it said that there's an effort
afoot to get closures into C, along with anonymous code blocks and
various other things. I think that is spectacularly misguided; if they
want Lisp, they know where to find it.)
/~\ The ASCII Mouse
\ / Ribbon Campaign
X Against HTML mouse at
rodents-montreal.org
/ \ Email! 7D C8 61 52 5D E7 2D 39 4E F1 31 3E E8 B3 27 4B