Non-local variable: Difference between revisions

Content deleted Content added
style refactor
m change source to syntaxhighlight
Line 6:
=== Nested functions === <!-- Please do NOT add the same example in other languages to this article. These two examples suffice to get the point across. Wikipedia is not a source code repository. -->
In the Python 3 example that follows there is a nested function <code>inner</code> defined in the scope of another function <code>outer</code>. The variable <code>x</code> is local to <code>outer</code>, but non-local to <code>inner</code> (nor is it global):
<sourcesyntaxhighlight lang=python3>
def outer():
x = 1
Line 14:
print(x)
return inner
</syntaxhighlight>
</source>
 
In Javascript, the locality of a variable is determined by the closest <code>var</code> statement for this variable. In the following example, <code>x</code> is local to <code>outer</code> as it contains a <code> var x</code> statement, while <code>inner</code> doesn't. Therefore, x is non-local to <code>inner</code>:
<sourcesyntaxhighlight lang=javascript>
function outer() {
var x = 1;
Line 26:
return inner;
}
</syntaxhighlight>
</source>
 
=== Anonymous functions === <!-- Please do NOT add the same example in other languages to this article. These examples suffice to get the point across. Wikipedia is not a source code repository. -->
In the Haskell example that follows the variable <code>c</code> is non-local in the anonymous function <code>\x -> x + c</code>:
<sourcesyntaxhighlight lang=haskell>
outer = let c = 1 in map (\x -> x + c) [1, 2, 3, 4, 5]
</syntaxhighlight>
</source>
 
== Implementation issues ==