views:

301

answers:

2

I've seen the term "lexical variable" a few times, mostly in the context of closures. Paul Graham uses the term in his books on Lisp referring to variables defined using the let expression.

I understand that lexical scoping is another name for static scoping. Is lexical variable just a variable that is visible in a program unit's referencing environment?

I hope to use this term to impress my friends and family this holiday season, can someone help me out?

A: 

A lexical variable is visible in a program unit's referencing environment, but not all variables that are visible in a program unit's referencing environment are necessarily lexical variables.

Basically, a lexical variable is one that is specific to the scope where it is defined. In a language like Perl, you essentially have two namespaces masked on top of each other: the underlying dynamic package namespace, and the overlaid lexical namespace. So $foo could refer to either, depending solely on whether it's been declared lexically.

chaos
So would it be safe to say that the terms "lexical variable" and "local variable" are interchangeable? With lexical being somewhat more precise?
Tim Merrifield
Nope. Perl has scope-localized variables that aren't lexical (they're implemented in the package namespace), using the local() keyword.
chaos
+3  A: 

A lexical variable is a variable that can only be referenced (by name) within its lexical scope. In other words, the scope of the variable is defined by the text of the program, not the dynamics of the program's execution. The variable and the value bound to it may have extent (life) beyond the lexical scope, e.g., if it is captured in a closure.

See this description of scope and extent.

Doug Currie