Non-local variable

Uses your system voice; voice and rate in settings.

Snapshot

≈ 3 min read

Names in other languages

No names in other languages are held for this entry yet.

Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.

In programming language theory, a non-local variable is a variable that is not defined in the local scope. While the term can refer to global variables, it is primarily used in the context of nested and anonymous functions where some variables can be in neither the local nor the global scope. In Lua they are called the upvalues of the function.

Examples

Nested functions

In the Python 3 example that follows there is a nested function inner defined in the scope of another function outer . The variable x is local to outer , but non-local to inner (nor is it global): from typing import Callable def outer() -> Callable[[], None]: x: int = 1 def inner() -> None: nonlocal x x += 1 print(x) return inner In JavaScript, the locality of a variable is determined by the closest var statement for this variable. In the following example, x is local to outer as it contains a var x statement, while inner doesn't. Therefore, x is non-local to inner : function outer() { var x = 1; function inner() { x += 1; console.log(x); } return inner; }

Anonymous functions

In the Haskell example that follows the variable c is non-local in the anonymous function \x -> x + c : outer = let c = 1 in map (\x -> x + c) [1, 2, 3, 4, 5]

In programming language theory, a non-local variable is a variable that is not defined in the local scope. While the term can refer to global variables, it is primarily used in the context of nested and anonymous functions where some variables can be in neither the local nor the global scope. In Lua they are called the upvalues of the function. from typing import Callable def outer() -> Callable[[], None]: x: int = 1 def inner() -> None: nonlocal x x += 1 print(x) return inner In JavaScript, the locality of a variable is determined by the closest var statement for this variable. In the following example, x is local to outer as it contains a var x statement, while inner doesn't. Therefore, x is non-local to inner : function outer() { var x = 1; function inner() { x += 1; console.log(x); } return inner; } outer = let c = 1 in map (\x -> x + c) [1, 2, 3, 4, 5]

Notes

Text derived from https://en.wikipedia.org/w/index.php?oldid=1310963400 under CC BY-SA 4.0; modifications have been made.

Sources cited in this revision

1 named source(s) extracted from the cited revision. A source with no author is shown by its publication; nothing is invented.