"Real world language" is a difficult measure to gauge objectively, but I'll give it a try since after all I also lack a CS background (EE major here) and am a little self-taught;-)
In many languages, a function "sees" more than one "scope" (group) of variables -- not only its local variables, and that of the module or namespace it's in, but also (if it's within another function) the local variables of the function that contains it.
So, for example (in Python, but many other languages work similarly!):
def outer(haystack):
def inner(needle):
eldeen = needle[::-1]
return (needle in haystack) or (eldeen in haystack)
return [x for x in ['gold','silver','diamond','straw'] if inner(x)]
inner
can "see" haystack
without needing to see it as an argument, just because its containing function outer
has haystack
"in scope" (i.e. "visible"). So far, so clear, I hope -- and this isn't yet about closures, it's about lexical scoping.
Now suppose the outer function (in a language treating functions as first-class objects, and in particular allowing them to be returned as results of other functions) the outer function returns the inner one instead of just calling it internally (in Python, that's for example what usually happens when you use decorator syntax @something
).
How can the inner function (returned as a result) still refer to the outer function's variable, since the outer function has finished?
The answer is exactly this "closure" business -- those variables from the outer function which the inner (returned) function may still need are preserved and attached as attributes of the inner-function object that's returned.