Scope modifiers: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 11: Line 11:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V x = ‘From global scope’
<syntaxhighlight lang="11l">V x = ‘From global scope’


F outerfunc()
F outerfunc()
Line 29: Line 29:
print(scoped_global())
print(scoped_global())


outerfunc()</lang>
outerfunc()</syntaxhighlight>


{{out}}
{{out}}
Line 44: Line 44:
Assemblers have different syntax for local labels, usually a period or an @ sign is used.
Assemblers have different syntax for local labels, usually a period or an @ sign is used.
Example of a macro definition that uses a local label:
Example of a macro definition that uses a local label:
<lang 6502asm>macro LDIR,source,dest,count
<syntaxhighlight lang="6502asm">macro LDIR,source,dest,count
;LoaD, Increment, Repeat
;LoaD, Increment, Repeat
lda #<source
lda #<source
Line 65: Line 65:
dex
dex
bne \@ ;repeat until x=0
bne \@ ;repeat until x=0
endm</lang>
endm</syntaxhighlight>


The assembler calculates the necessary byte offset for the branch to work, by counting the bytes each instruction takes between the label and the branch to that label. That value becomes the operand of the <code>BNE</code> instruction in the macro. Since there is no label associated with any particular instance of \@ you cannot for example use <code>JMP \@</code> outside the macro to go there. (Of course, if you know the exact memory location an instruction is located at, you can jump there by specifying a numeric address, no matter what scope rules the assembler imposes.)
The assembler calculates the necessary byte offset for the branch to work, by counting the bytes each instruction takes between the label and the branch to that label. That value becomes the operand of the <code>BNE</code> instruction in the macro. Since there is no label associated with any particular instance of \@ you cannot for example use <code>JMP \@</code> outside the macro to go there. (Of course, if you know the exact memory location an instruction is located at, you can jump there by specifying a numeric address, no matter what scope rules the assembler imposes.)
Line 72: Line 72:
Like most assembly languages, 68000 Assembly has no concept of scope in the traditional sense, as it uses a linear memory model and allows free jumping to any memory address. However, the assembler can implement scope with local labels. Syntax varies depending on the assembler, but some use a period <code>.</code> before a label name to indicate a local label that is only visible between two non-local labels.
Like most assembly languages, 68000 Assembly has no concept of scope in the traditional sense, as it uses a linear memory model and allows free jumping to any memory address. However, the assembler can implement scope with local labels. Syntax varies depending on the assembler, but some use a period <code>.</code> before a label name to indicate a local label that is only visible between two non-local labels.


<lang 68000devpac>foo:
<syntaxhighlight lang="68000devpac">foo:
MOVE.L #$DEADBEEF,D0
MOVE.L #$DEADBEEF,D0
MOVE.L #$16-1,D1
MOVE.L #$16-1,D1
.bar:
.bar:
DBRA D1,.bar ;any code outside "foo" cannot JMP, Bxx, BRA, or JSR/BSR here by using the name ".bar"
DBRA D1,.bar ;any code outside "foo" cannot JMP, Bxx, BRA, or JSR/BSR here by using the name ".bar"
RTS</lang>
RTS</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
Line 83: Line 83:
In [[Ada]] declarative region of a package has publicly visible and private parts.
In [[Ada]] declarative region of a package has publicly visible and private parts.
The private part is introduced by '''private''':
The private part is introduced by '''private''':
<lang ada>package P is
<syntaxhighlight lang="ada">package P is
... -- Declarations placed here are publicly visible
... -- Declarations placed here are publicly visible
private
private
... -- These declarations are visible only to the children of P
... -- These declarations are visible only to the children of P
end P;</lang>
end P;</syntaxhighlight>
Correspondingly a type or object declaration may be incomplete in the public part providing an official interface. For example:
Correspondingly a type or object declaration may be incomplete in the public part providing an official interface. For example:
<lang ada>package P is
<syntaxhighlight lang="ada">package P is
type T is private; -- No components visible
type T is private; -- No components visible
procedure F (X : in out T); -- The only visible operation
procedure F (X : in out T); -- The only visible operation
Line 99: Line 99:
procedure V (X : in out T); -- Operation used only by children
procedure V (X : in out T); -- Operation used only by children
N : constant T := (Component => 0); -- Constant implementation
N : constant T := (Component => 0); -- Constant implementation
end P;</lang>
end P;</syntaxhighlight>


===Bodies (invisible declarations)===
===Bodies (invisible declarations)===
The keyword '''body''' applied to the packages, protected objects and tasks. It specifies an implementation of the corresponding entity invisible from anywhere else:
The keyword '''body''' applied to the packages, protected objects and tasks. It specifies an implementation of the corresponding entity invisible from anywhere else:
<lang ada>package body P is
<syntaxhighlight lang="ada">package body P is
-- The implementation of P, invisible to anybody
-- The implementation of P, invisible to anybody
procedure W (X : in out T); -- Operation used only internally
procedure W (X : in out T); -- Operation used only internally
end P;</lang>
end P;</syntaxhighlight>
===Private children===
===Private children===
The keyword '''private''' can be applied to the whole package, a child of another package:
The keyword '''private''' can be applied to the whole package, a child of another package:
<lang ada>private package P.Q is
<syntaxhighlight lang="ada">private package P.Q is
... -- Visible to the siblings only
... -- Visible to the siblings only
private
private
... -- Visible to the children only
... -- Visible to the children only
end P.Q;</lang>
end P.Q;</syntaxhighlight>
This package can be then used only by private siblings of the same parent P.
This package can be then used only by private siblings of the same parent P.


Line 127: Line 127:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{AutoHotkey case}}
{{AutoHotkey case}}
<lang AutoHotkey>singleton = "global variable"
<syntaxhighlight lang="autohotkey">singleton = "global variable"


assume_global()
assume_global()
Line 151: Line 151:
_%member% := ""
_%member% := ""
Return (_%member%)
Return (_%member%)
}</lang>
}</syntaxhighlight>


=={{header|Axe}}==
=={{header|Axe}}==
Line 159: Line 159:
==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
All variables are global by default, except the parameter which is local to the function. There are no scope modifiers.
All variables are global by default, except the parameter which is local to the function. There are no scope modifiers.
<lang ApplesoftBasic> 10 X = 1
<syntaxhighlight lang="applesoftbasic"> 10 X = 1
20 DEF FN F(X) = X
20 DEF FN F(X) = X
30 DEF FN G(N) = X
30 DEF FN G(N) = X
40 PRINT FN F(2)
40 PRINT FN F(2)
50 PRINT FN G(3)</lang>
50 PRINT FN G(3)</syntaxhighlight>
{{out}}
{{out}}
<pre>2
<pre>2
Line 176: Line 176:


The scope modifier PRIVATE declares a variable static to a function; it sets the value to zero/NULL initially.
The scope modifier PRIVATE declares a variable static to a function; it sets the value to zero/NULL initially.
<lang bbcbasic> var1$ = "Global1"
<syntaxhighlight lang="bbcbasic"> var1$ = "Global1"
var2$ = "Global2"
var2$ = "Global2"
Line 208: Line 208:
PRINT "var2$ = """ var2$ """"
PRINT "var2$ = """ var2$ """"
ENDPROC</lang>
ENDPROC</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 242: Line 242:
One can think of each identifier as a stack. Function parameters and local identifiers are pushed onto the stack and shadow the values of identifiers with the same names from outer scopes. They are popped from the stack when the function returns. Thus a function that is called from another function has access to the local identifiers and parameters of its caller if itself doesn't use the same name as a local identifier/parameter. In other words, always the innermost value (the value at the top of the stack) for each identifier is visible, regardless of the scope level where it is accessed.
One can think of each identifier as a stack. Function parameters and local identifiers are pushed onto the stack and shadow the values of identifiers with the same names from outer scopes. They are popped from the stack when the function returns. Thus a function that is called from another function has access to the local identifiers and parameters of its caller if itself doesn't use the same name as a local identifier/parameter. In other words, always the innermost value (the value at the top of the stack) for each identifier is visible, regardless of the scope level where it is accessed.


<lang bc>define g(a) {
<syntaxhighlight lang="bc">define g(a) {
auto b
auto b
Line 281: Line 281:
"Global scope (before call): b = "; b
"Global scope (before call): b = "; b
"Global scope (before call): c = "; c
"Global scope (before call): c = "; c
"Global scope (before call): d = "; d</lang>
"Global scope (before call): d = "; d</syntaxhighlight>


{{Out}}
{{Out}}
Line 308: Line 308:
Undeclared variables have always global scope and declared variables have always dynamic scope. Also the function argument (always called "arg" and never explicitly declared) has always dynamic scope. The Bracmat program contained in file "lex.bra" (see Bracmat on GitHub) analyses another Bracmat program to find the places where variables are not in lexical scope. Following the suggestions to declare such variables (and to remove declared, but unused variables) will improve the readability of the analysed code.
Undeclared variables have always global scope and declared variables have always dynamic scope. Also the function argument (always called "arg" and never explicitly declared) has always dynamic scope. The Bracmat program contained in file "lex.bra" (see Bracmat on GitHub) analyses another Bracmat program to find the places where variables are not in lexical scope. Following the suggestions to declare such variables (and to remove declared, but unused variables) will improve the readability of the analysed code.


<lang bracmat> 67:?x {x has global scope}
<syntaxhighlight lang="bracmat"> 67:?x {x has global scope}
& 77:?y { y has global scope }
& 77:?y { y has global scope }
& ( double
& ( double
Line 320: Line 320:
& double$
& double$
& !x+!y
& !x+!y
)</lang>
)</syntaxhighlight>


"Variables" in lambda expressions have lexical scope. But can of course not be varied.
"Variables" in lambda expressions have lexical scope. But can of course not be varied.


<lang bracmat>/('(x./('(y.$x+$y))$3))$5 { x and y have lexical scope }</lang>
<syntaxhighlight lang="bracmat">/('(x./('(y.$x+$y))$3))$5 { x and y have lexical scope }</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
Line 330: Line 330:


'''file1.c'''
'''file1.c'''
<lang c>int a; // a is global
<syntaxhighlight lang="c">int a; // a is global
static int p; // p is "locale" and can be seen only from file1.c
static int p; // p is "locale" and can be seen only from file1.c


Line 353: Line 353:
v = v * 1.02; // update global v
v = v * 1.02; // update global v
// ...
// ...
}</lang>
}</syntaxhighlight>


'''file2.c'''
'''file2.c'''
<lang c>float v; // a global to be used from file1.c too
<syntaxhighlight lang="c">float v; // a global to be used from file1.c too
static int p; // a file-scoped p; nothing to share with static p
static int p; // a file-scoped p; nothing to share with static p
// in file1.c
// in file1.c
Line 363: Line 363:
// normally these things go into a header.h
// normally these things go into a header.h


// ...</lang>
// ...</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>public //visible to anything.
<syntaxhighlight lang="csharp">public //visible to anything.
protected //visible to current class and to derived classes.
protected //visible to current class and to derived classes.
internal //visible to anything inside the same assembly (.dll/.exe).
internal //visible to anything inside the same assembly (.dll/.exe).
Line 383: Line 383:
//private | Yes | No | No || No | No
//private | Yes | No | No || No | No
// C# 7.2:
// C# 7.2:
//private protected | Yes | Yes | No || No | No</lang>
//private protected | Yes | Yes | No || No | No</syntaxhighlight>
If no modifier is specified, it defaults to the most restrictive one.<br/>
If no modifier is specified, it defaults to the most restrictive one.<br/>
In case of top-level classes/structs/interfaces/enums this means internal, otherwise it means private.
In case of top-level classes/structs/interfaces/enums this means internal, otherwise it means private.
Line 389: Line 389:
Special case: explicit interface implementation.<br/>
Special case: explicit interface implementation.<br/>
When a class explicitly implements an interface method, it is 'hidden' and that method can only be accessed through the interface:
When a class explicitly implements an interface method, it is 'hidden' and that method can only be accessed through the interface:
<lang csharp>public interface IPrinter
<syntaxhighlight lang="csharp">public interface IPrinter
{
{
void Print();
void Print();
Line 410: Line 410:
}
}
}
}
</syntaxhighlight>
</lang>
Other declarations follow lexical scoping.<br/>
Other declarations follow lexical scoping.<br/>
Visibility is determined by the enclosing braces { }<br/>
Visibility is determined by the enclosing braces { }<br/>
Line 432: Line 432:
The next example declaims that <code>*bug*</code> has dynamic scope. Meanwhile, <code>shape</code> has lexical scope.
The next example declaims that <code>*bug*</code> has dynamic scope. Meanwhile, <code>shape</code> has lexical scope.


<lang lisp>;; *bug* shall have a dynamic binding.
<syntaxhighlight lang="lisp">;; *bug* shall have a dynamic binding.
(declaim (special *bug*))
(declaim (special *bug*))


Line 443: Line 443:
(let ((shape "circle") (*bug* "cockroach"))
(let ((shape "circle") (*bug* "cockroach"))
(format t "~%Put ~A in your ~A..." *bug* shape)
(format t "~%Put ~A in your ~A..." *bug* shape)
(speak))))</lang>
(speak))))</syntaxhighlight>


The function <code>speak</code> tries to use both <code>*bug*</code> and <code>shape</code>. For lexical scope, the value comes from where the program ''defines'' <code>speak</code>. For dynamic scope, the value comes from where the program ''calls'' <code>speak</code>. So <code>speak</code> always uses the same "triangle", but can use a different bug.
The function <code>speak</code> tries to use both <code>*bug*</code> and <code>shape</code>. For lexical scope, the value comes from where the program ''defines'' <code>speak</code>. For dynamic scope, the value comes from where the program ''calls'' <code>speak</code>. So <code>speak</code> always uses the same "triangle", but can use a different bug.
Line 455: Line 455:


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>private</lang>
<syntaxhighlight lang="delphi">private</syntaxhighlight>
Can only be seen inside declared class.
Can only be seen inside declared class.


<lang Delphi>protected</lang>
<syntaxhighlight lang="delphi">protected</syntaxhighlight>
Can be seen in descendent classes.
Can be seen in descendent classes.


<lang Delphi>public</lang>
<syntaxhighlight lang="delphi">public</syntaxhighlight>
Can be seen from outside the class.
Can be seen from outside the class.


<lang Delphi>protected</lang>
<syntaxhighlight lang="delphi">protected</syntaxhighlight>
Same visibility as Public, but run time type information (RTTI) is generated, allowing these members to be viewed dynamically. Members need to be published in order to be streamed or shown in the Object Inspector.
Same visibility as Public, but run time type information (RTTI) is generated, allowing these members to be viewed dynamically. Members need to be published in order to be streamed or shown in the Object Inspector.


<lang Delphi>automated</lang>
<syntaxhighlight lang="delphi">automated</syntaxhighlight>
Same visibility as Public, and used for Automation Objects. This is currently only maintained for backward compatibility.
Same visibility as Public, and used for Automation Objects. This is currently only maintained for backward compatibility.


<lang Delphi>strict private
<syntaxhighlight lang="delphi">strict private
strict protected</lang>
strict protected</syntaxhighlight>
Private and Protected members of a class are visible to other classes declared in the same unit. The "strict" modifier was added in Delphi 2005 to treat public and private members as private and protected, even from classes declared in the same unit.
Private and Protected members of a class are visible to other classes declared in the same unit. The "strict" modifier was added in Delphi 2005 to treat public and private members as private and protected, even from classes declared in the same unit.


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
Variables are lexically scoped in Déjà Vu. Doing a <code>set</code> or a <code>get</code> starts looking for <code>local</code> declarations in the current scope, going upward until the global scope. One can use <code>setglobal</code> and <code>getlocal</code> to bypass this process, and only look at the global scope.
Variables are lexically scoped in Déjà Vu. Doing a <code>set</code> or a <code>get</code> starts looking for <code>local</code> declarations in the current scope, going upward until the global scope. One can use <code>setglobal</code> and <code>getlocal</code> to bypass this process, and only look at the global scope.
<lang dejavu>set :a "global"
<syntaxhighlight lang="dejavu">set :a "global"
if true:
if true:
!print a
!print a
Line 483: Line 483:
!print getglobal :a
!print getglobal :a
!print a
!print a
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>global
<pre>global
Line 505: Line 505:
* a global variable
* a global variable


<lang Eiffel>feature
<syntaxhighlight lang="eiffel">feature
some_procedure(int: INTEGER; char: CHARACTER)
some_procedure(int: INTEGER; char: CHARACTER)
local
local
Line 525: Line 525:
end
end


-- s, some_procedure and some_function have scope here</lang>
-- s, some_procedure and some_function have scope here</syntaxhighlight>


=={{header|Ela}}==
=={{header|Ela}}==
Variables in Ela are lexically scoped (pretty similar to Haskell) and can be declared using let/in and where bindings. Additionally Ela provides a 'private' scope modifier for global bindings:
Variables in Ela are lexically scoped (pretty similar to Haskell) and can be declared using let/in and where bindings. Additionally Ela provides a 'private' scope modifier for global bindings:


<lang ela>pi # private
<syntaxhighlight lang="ela">pi # private
pi = 3.14159
pi = 3.14159


sum # private
sum # private
sum x y = x + y</lang>
sum x y = x + y</syntaxhighlight>


Names declared with 'private' modifier are not visible outside of a module. All other bindings are visible and can be imported. It is an error to use 'private' modifier on local bindings.
Names declared with 'private' modifier are not visible outside of a module. All other bindings are visible and can be imported. It is an error to use 'private' modifier on local bindings.
Line 540: Line 540:
=={{header|Erlang}}==
=={{header|Erlang}}==
Erlang is lexically scoped. Variables, which must begin with an upper case letter, are only available inside their functions. Functions are only available inside their modules. Unless they are exported.
Erlang is lexically scoped. Variables, which must begin with an upper case letter, are only available inside their functions. Functions are only available inside their modules. Unless they are exported.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( a_module ).
-module( a_module ).


Line 550: Line 550:


add( N, N ) -> N + N.
add( N, N ) -> N + N.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 566: Line 566:


* If a variable is not explicitly defined its scope is local. This may be modified by using the keyword Shared. The effects are detailed by the comments in the sample code.
* If a variable is not explicitly defined its scope is local. This may be modified by using the keyword Shared. The effects are detailed by the comments in the sample code.
<lang FreeBASIC>'Declares a integer variable and reserves memory to accommodate it
<syntaxhighlight lang="freebasic">'Declares a integer variable and reserves memory to accommodate it
Dim As Integer baseAge = 10
Dim As Integer baseAge = 10
'Define a variable that has static storage
'Define a variable that has static storage
Line 591: Line 591:
test()
test()
Print person; " and "; friend; " are"; baseAge; " and"; baseAge + ageDiff + extraYears; " years old."
Print person; " and "; friend; " are"; baseAge; " and"; baseAge + ageDiff + extraYears; " years old."
Sleep</lang>
Sleep</syntaxhighlight>
{{out}}
{{out}}
<pre>Bob and Susan are 30 and 35 years old.
<pre>Bob and Susan are 30 and 35 years old.
Line 624: Line 624:
=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon data types are not declared and variables can take on any value; however, variables can be declared as to their scope. For more see [[Icon%2BUnicon/Intro#un-Declarations.2C_it.27s_all_about_Scope|un-Declarations it's all about scope]]. Additionally, Unicon supports classes with methods.
Icon and Unicon data types are not declared and variables can take on any value; however, variables can be declared as to their scope. For more see [[Icon%2BUnicon/Intro#un-Declarations.2C_it.27s_all_about_Scope|un-Declarations it's all about scope]]. Additionally, Unicon supports classes with methods.
<lang Icon>global var1 # used outside of procedures
<syntaxhighlight lang="icon">global var1 # used outside of procedures


procedure one() # a global procedure (the only kind)
procedure one() # a global procedure (the only kind)
local var2 # used inside of procedures
local var2 # used inside of procedures
static var3 # also used inside of procedures
static var3 # also used inside of procedures
end</lang>
end</syntaxhighlight>


Co-expressions (both languages) also redefine scope - any local variables referenced
Co-expressions (both languages) also redefine scope - any local variables referenced
Line 640: Line 640:
First approximation: All variables are either "global" in scope, or are local to the currently executing explicit definition. Local names shadow global names. J provides kinds of assignment -- assignment to a local name (<tt>=.</tt>) and assignment to a global name (<tt>=:</tt>). Shadowed global names ("global" names which have the same name as a name that has a local definition) can not be assigned to (because this is typically a programming mistake and can be easily avoided by performing the assignment in a different execution context). Here's an interactive session:
First approximation: All variables are either "global" in scope, or are local to the currently executing explicit definition. Local names shadow global names. J provides kinds of assignment -- assignment to a local name (<tt>=.</tt>) and assignment to a global name (<tt>=:</tt>). Shadowed global names ("global" names which have the same name as a name that has a local definition) can not be assigned to (because this is typically a programming mistake and can be easily avoided by performing the assignment in a different execution context). Here's an interactive session:


<lang J> A=: 1
<syntaxhighlight lang="j"> A=: 1
B=: 2
B=: 2
C=: 3
C=: 3
Line 656: Line 656:
2
2
D
D
|value error</lang>
|value error</syntaxhighlight>


Second approximation: J does not really have a global namespace. Instead, each object and each class has its own namespace. By default, interactive use updates the namespace for the class named 'base'. Further discussion of this issue is beyond the scope of this page.
Second approximation: J does not really have a global namespace. Instead, each object and each class has its own namespace. By default, interactive use updates the namespace for the class named 'base'. Further discussion of this issue is beyond the scope of this page.


=={{header|Java}}==
=={{header|Java}}==
<lang java>public //any class may access this member directly
<syntaxhighlight lang="java">public //any class may access this member directly


protected //only this class, subclasses of this class,
protected //only this class, subclasses of this class,
Line 695: Line 695:
}
}
//can use x and y here, but NOT z
//can use x and y here, but NOT z
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 709: Line 709:
<code> local x </code>introduces a new local variable x.
<code> local x </code>introduces a new local variable x.
<br /><br />
<br /><br />
<lang julia>
<syntaxhighlight lang="julia">
julia> function foo(n)
julia> function foo(n)
x = 0
x = 0
Line 722: Line 722:
julia> foo(10)
julia> foo(10)
0
0
</syntaxhighlight>
</lang>
Julia also has scopes based on modules. Variables within a standard module such as <code>MyModule; x = 0; end</code>need to be referred to with the module name prefix, such as <code>MyModule.x</code>, unless the variable is exported from the module with the <code> export</code> keyword.
Julia also has scopes based on modules. Variables within a standard module such as <code>MyModule; x = 0; end</code>need to be referred to with the module name prefix, such as <code>MyModule.x</code>, unless the variable is exported from the module with the <code> export</code> keyword.


Line 737: Line 737:


4. Kotlin does not have static members as such but instead has 'companion objects' whose members can be accessed using the class name, rather than a reference to a particular object of that class. The following is a simple example of their use:
4. Kotlin does not have static members as such but instead has 'companion objects' whose members can be accessed using the class name, rather than a reference to a particular object of that class. The following is a simple example of their use:
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


class SomeClass {
class SomeClass {
Line 758: Line 758:
println(sc2.id)
println(sc2.id)
println(SomeClass.objectsCreated)
println(SomeClass.objectsCreated)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 784: Line 784:
=={{header|Logo}}==
=={{header|Logo}}==
Traditional Logo has dynamic scope for all symbols except for parameters, ostensibly so that it is easy to inspect bound values in an educational setting. UCB Logo also has a LOCAL syntax for declaring a dynamically scoped variable visible to a procedure and those procedures it calls.
Traditional Logo has dynamic scope for all symbols except for parameters, ostensibly so that it is easy to inspect bound values in an educational setting. UCB Logo also has a LOCAL syntax for declaring a dynamically scoped variable visible to a procedure and those procedures it calls.
<lang logo>
<syntaxhighlight lang="logo">
make "g 5 ; global
make "g 5 ; global


Line 800: Line 800:
localmake "h 5 ; hides global :h within this procedure and those it calls
localmake "h 5 ; hides global :h within this procedure and those it calls
end
end
</syntaxhighlight>
</lang>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
Logtalk supports scope modifiers in predicate declarations and entity (object, category, or protocol) relations. By default, predicates are local (i.e. like private but invisible to the reflection mechanisms) and entity relations are public (i.e. not change to inherited predicate declarations is applied).
Logtalk supports scope modifiers in predicate declarations and entity (object, category, or protocol) relations. By default, predicates are local (i.e. like private but invisible to the reflection mechanisms) and entity relations are public (i.e. not change to inherited predicate declarations is applied).
<lang logtalk>
<syntaxhighlight lang="logtalk">
:- public(foo/1). % predicate can be called from anywhere
:- public(foo/1). % predicate can be called from anywhere


Line 819: Line 819:
:- protocol(extended, % no change to the scope of the predicates inherited from the extended protocol
:- protocol(extended, % no change to the scope of the predicates inherited from the extended protocol
extends(public::minimal)).
extends(public::minimal)).
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
In Lua, variables are global by default, but can be modified to be local to the block in which they are declared.
In Lua, variables are global by default, but can be modified to be local to the block in which they are declared.
<lang lua>foo = "global" -- global scope
<syntaxhighlight lang="lua">foo = "global" -- global scope
print(foo)
print(foo)
local foo = "local module" -- local to the current block (which is the module)
local foo = "local module" -- local to the current block (which is the module)
Line 838: Line 838:
end -- close the block (and thus its scope)
end -- close the block (and thus its scope)
print(foo) -- module-level local still exists
print(foo) -- module-level local still exists
print(_G.foo) -- global still exists</lang>
print(_G.foo) -- global still exists</syntaxhighlight>
{{out}}
{{out}}
<pre>global
<pre>global
Line 864: Line 864:
We have to use <= to assign new values to global variables, or to member of groups inside a module inside a group. See ResetValues in Group Alfa.
We have to use <= to assign new values to global variables, or to member of groups inside a module inside a group. See ResetValues in Group Alfa.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
M=1000
M=1000
Line 942: Line 942:
Modules ? ' list of modules show two: A and A.Checkit
Modules ? ' list of modules show two: A and A.Checkit
Print Module$ ' print A
Print Module$ ' print A
</syntaxhighlight>
</lang>
Subs are searched first time for current module/function, or from parent code, and stored in a list as name, internal number of code source and position in code. Modules can replaced (we sy decorated) with other modules, before call (see CheckThis changed for a call with ChangeOther).
Subs are searched first time for current module/function, or from parent code, and stored in a list as name, internal number of code source and position in code. Modules can replaced (we sy decorated) with other modules, before call (see CheckThis changed for a call with ChangeOther).


Line 949: Line 949:
Threads are part of modules/functions. They have own stack of values. own static variables, but they see everything like code in module:
Threads are part of modules/functions. They have own stack of values. own static variables, but they see everything like code in module:


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
Module CheckSub {
Module CheckSub {
Line 1,004: Line 1,004:
}
}
Call Alfa
Call Alfa
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Module -> localize names of variables (lexical scoping)
<syntaxhighlight lang="mathematica">Module -> localize names of variables (lexical scoping)
Block -> localize values of variables (dynamic scoping)
Block -> localize values of variables (dynamic scoping)
Module creates new symbols:
Module creates new symbols:
Line 1,020: Line 1,020:
Print[x]
Print[x]
->0
->0
->7</lang>
->7</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
MUMPS variable can be in a local scope if they are declared as NEW within a subroutine. Otherwise variables are accessible to all levels.
MUMPS variable can be in a local scope if they are declared as NEW within a subroutine. Otherwise variables are accessible to all levels.
<lang MUMPS>OUTER
<syntaxhighlight lang="mumps">OUTER
SET OUT=1,IN=0
SET OUT=1,IN=0
WRITE "OUT = ",OUT,!
WRITE "OUT = ",OUT,!
Line 1,038: Line 1,038:
WRITE "IN (inner scope) = ",IN,!
WRITE "IN (inner scope) = ",IN,!
KILL OUT
KILL OUT
QUIT</lang>
QUIT</syntaxhighlight>
Execution:<pre>
Execution:<pre>
USER>D ^SCOPE
USER>D ^SCOPE
Line 1,050: Line 1,050:
=={{header|Nim}}==
=={{header|Nim}}==
Identifiers annotated with a <code>*</code> are accessible from other modules
Identifiers annotated with a <code>*</code> are accessible from other modules
<lang nim>proc foo = echo "foo" # hidden
<syntaxhighlight lang="nim">proc foo = echo "foo" # hidden
proc bar* = echo "bar" # acessible
proc bar* = echo "bar" # acessible


type MyObject = object
type MyObject = object
name*: string # accessible
name*: string # accessible
secretAge: int # hidden</lang>
secretAge: int # hidden</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Line 1,064: Line 1,064:
Pascal does not have scope modifiers.
Pascal does not have scope modifiers.
Regular block scopes are defined simply by virtue of the declaration’s position:
Regular block scopes are defined simply by virtue of the declaration’s position:
<lang pascal>procedure super;
<syntaxhighlight lang="pascal">procedure super;
var
var
f: boolean;
f: boolean;
Line 1,092: Line 1,092:
// here, `c`, `f`, and `x`, as well as,
// here, `c`, `f`, and `x`, as well as,
// `nestedProcedure`, `commonTask`, `fooBar` and `super` are available
// `nestedProcedure`, `commonTask`, `fooBar` and `super` are available
end;</lang>
end;</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
Line 1,101: Line 1,101:
There are four kinds of declaration that can influence the scoping of a particular variable: <code>our</code>, <code>my</code>, <code>state</code>, and <code>local</code>. <code>our</code> makes a package variable lexically available. Its primary use is to allow easy access to package variables under stricture.
There are four kinds of declaration that can influence the scoping of a particular variable: <code>our</code>, <code>my</code>, <code>state</code>, and <code>local</code>. <code>our</code> makes a package variable lexically available. Its primary use is to allow easy access to package variables under stricture.


<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
$x = 1; # Compilation error.
$x = 1; # Compilation error.
our $y = 2;
our $y = 2;
Line 1,109: Line 1,109:
our $z = 3;
our $z = 3;
package Bar;
package Bar;
print "$z\n"; # Refers to $Foo::z.</lang>
print "$z\n"; # Refers to $Foo::z.</syntaxhighlight>


<code>my</code> creates a new lexical variable, independent of any package. It's destroyed as soon as it falls out of scope, and each execution of the statement containing the <code>my</code> creates a new, independent variable.
<code>my</code> creates a new lexical variable, independent of any package. It's destroyed as soon as it falls out of scope, and each execution of the statement containing the <code>my</code> creates a new, independent variable.


<lang perl>package Foo;
<syntaxhighlight lang="perl">package Foo;
my $fruit = 'apple';
my $fruit = 'apple';
package Bar;
package Bar;
Line 1,125: Line 1,125:
our $fruit = 'orange';
our $fruit = 'orange';
print "$fruit\n"; # Prints "orange"; refers to $Bar::fruit.
print "$fruit\n"; # Prints "orange"; refers to $Bar::fruit.
# The first $fruit is inaccessible.</lang>
# The first $fruit is inaccessible.</syntaxhighlight>


<code>state</code> is like <code>my</code> but creates a variable only once. The variable's value is remembered between visits to the enclosing scope. The <code>state</code> feature is only available in perl 5.9.4 and later, and must be activated with <code>use feature 'state';</code> or a <code>use</code> demanding a sufficiently recent perl.
<code>state</code> is like <code>my</code> but creates a variable only once. The variable's value is remembered between visits to the enclosing scope. The <code>state</code> feature is only available in perl 5.9.4 and later, and must be activated with <code>use feature 'state';</code> or a <code>use</code> demanding a sufficiently recent perl.


<lang perl>use 5.10.0;
<syntaxhighlight lang="perl">use 5.10.0;


sub count_up
sub count_up
Line 1,138: Line 1,138:


count_up; # Prints "13".
count_up; # Prints "13".
count_up; # Prints "14".</lang>
count_up; # Prints "14".</syntaxhighlight>


<code>local</code> gives a package variable a new value for the duration of the current ''dynamic'' scope.
<code>local</code> gives a package variable a new value for the duration of the current ''dynamic'' scope.


<lang perl>our $camelid = 'llama';
<syntaxhighlight lang="perl">our $camelid = 'llama';


sub phooey
sub phooey
Line 1,158: Line 1,158:


do_phooey; # Prints "alpaca".
do_phooey; # Prints "alpaca".
phooey; # Prints "llama".</lang>
phooey; # Prints "llama".</syntaxhighlight>


Usually, <code>my</code> is preferable to <code>local</code>, but one thing <code>local</code> can do that <code>my</code> can't is affect the special punctuation variables, like <code>$/</code> and <code>$"</code>. Actually, in perl 5.9.1 and later, <code>my $_</code> is specially allowed and works as you would expect.
Usually, <code>my</code> is preferable to <code>local</code>, but one thing <code>local</code> can do that <code>my</code> can't is affect the special punctuation variables, like <code>$/</code> and <code>$"</code>. Actually, in perl 5.9.1 and later, <code>my $_</code> is specially allowed and works as you would expect.
Line 1,166: Line 1,166:
Identifiers are private by default, ie restricted to a single file, or they can be made global by prefixing the definition with the global keyword, outside of routines only - everything declared inside a routine is always private to that routine. Should a forward declaraion of a routine exist, it must match the actual definition in terms of presence/absence of a global prefix, as well as parameter types, etc.
Identifiers are private by default, ie restricted to a single file, or they can be made global by prefixing the definition with the global keyword, outside of routines only - everything declared inside a routine is always private to that routine. Should a forward declaraion of a routine exist, it must match the actual definition in terms of presence/absence of a global prefix, as well as parameter types, etc.


<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">forward</span> <span style="color: #008080;">function</span> <span style="color: #000000;">localf</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- not normally necesssary, but will not harm</span>
<span style="color: #008080;">forward</span> <span style="color: #008080;">function</span> <span style="color: #000000;">localf</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- not normally necesssary, but will not harm</span>
<span style="color: #008080;">forward</span> <span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #000000;">globalf</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- ""</span>
<span style="color: #008080;">forward</span> <span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #000000;">globalf</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- ""</span>
Line 1,177: Line 1,177:
<span style="color: #008080;">return</span> <span style="color: #000000;">2</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


Here, localf() can only be invoked from within the same file, but globalf() can be invoked from any other file
Here, localf() can only be invoked from within the same file, but globalf() can be invoked from any other file
Line 1,186: Line 1,186:
Namespaces for specific (entire) files can be used to qualify global identifiers, should there be a name clash between several files.
Namespaces for specific (entire) files can be used to qualify global identifiers, should there be a name clash between several files.


<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">include</span> <span style="color: #000000;">somefile</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> <span style="color: #000000;">as</span> <span style="color: #000000;">xxx</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">somefile</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> <span style="color: #000000;">as</span> <span style="color: #000000;">xxx</span>
<span style="color: #000080;font-style:italic;">-- alternatively, within somefile.e:</span>
<span style="color: #000080;font-style:italic;">-- alternatively, within somefile.e:</span>
Line 1,192: Line 1,192:
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">xxx</span><span style="color: #0000FF;">:</span><span style="color: #000000;">globalf</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- call a global function named globalf, specifically the one declared in somefile.e</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">xxx</span><span style="color: #0000FF;">:</span><span style="color: #000000;">globalf</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- call a global function named globalf, specifically the one declared in somefile.e</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


Note however that one of the main reasons for namespaces is to avoid having to amend any included (3rd party)
Note however that one of the main reasons for namespaces is to avoid having to amend any included (3rd party)
Line 1,239: Line 1,239:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
Variables can have a specific scope, which is one of '''global''', '''local''', '''script''', '''private'''. Variables with the same name can exist in different scopes and are shadowed by child scopes. The scope of a variable can be directly prefixed to the variable name:
Variables can have a specific scope, which is one of '''global''', '''local''', '''script''', '''private'''. Variables with the same name can exist in different scopes and are shadowed by child scopes. The scope of a variable can be directly prefixed to the variable name:
<lang powershell>$a = "foo" # global scope
<syntaxhighlight lang="powershell">$a = "foo" # global scope
function test {
function test {
$a = "bar" # local scope
$a = "bar" # local scope
Write-Host Local: $a # "bar" - local variable
Write-Host Local: $a # "bar" - local variable
Write-Host Global: $global:a # "foo" - global variable
Write-Host Global: $global:a # "foo" - global variable
}</lang>
}</syntaxhighlight>
The various cmdlets dealing with variables also have a '''–Scope''' parameter, enabling one to specify a relative or absolute scope for the variable to be manipulated.
The various cmdlets dealing with variables also have a '''–Scope''' parameter, enabling one to specify a relative or absolute scope for the variable to be manipulated.


Line 1,255: Line 1,255:


* If a variable is not explicitly defined its scope is local to one of the aforementioned areas. This may be modified by using one of the keywords: <tt>Global</tt>, <tt>Protected</tt>, or <tt>Shared</tt>. The effects are detailed by the comments in the sample code.
* If a variable is not explicitly defined its scope is local to one of the aforementioned areas. This may be modified by using one of the keywords: <tt>Global</tt>, <tt>Protected</tt>, or <tt>Shared</tt>. The effects are detailed by the comments in the sample code.
<lang PureBasic>;define a local integer variable by simply using it
<syntaxhighlight lang="purebasic">;define a local integer variable by simply using it
baseAge.i = 10
baseAge.i = 10
;explicitly define local strings
;explicitly define local strings
Line 1,286: Line 1,286:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
{{out}}
{{out}}
<pre>Bob and Susan are 30 and 35 years old.
<pre>Bob and Susan are 30 and 35 years old.
Line 1,299: Line 1,299:
In the example below the name <code>x</code> is defined at various scopes and given a different value dependent on its scope. The innermost functions demonstrate how the scope modifiers give acccess to the name from different scopes:
In the example below the name <code>x</code> is defined at various scopes and given a different value dependent on its scope. The innermost functions demonstrate how the scope modifiers give acccess to the name from different scopes:


<lang python>>>> x="From global scope"
<syntaxhighlight lang="python">>>> x="From global scope"
>>> def outerfunc():
>>> def outerfunc():
x = "From scope at outerfunc"
x = "From scope at outerfunc"
Line 1,328: Line 1,328:
scoped_global scope gives x = From global scope
scoped_global scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From global scope
>>></lang>
>>></syntaxhighlight>
More information on the scope modifiers can be found [http://docs.python.org/3.0/reference/simple_stmts.html#grammar-token-global_stmt here].
More information on the scope modifiers can be found [http://docs.python.org/3.0/reference/simple_stmts.html#grammar-token-global_stmt here].


Line 1,340: Line 1,340:
up the chain of parent environments.
up the chain of parent environments.


<lang R>X <- "global x"
<syntaxhighlight lang="r">X <- "global x"
f <- function() {
f <- function() {
x <- "local x"
x <- "local x"
Line 1,346: Line 1,346:
}
}
f() #prints "local x"
f() #prints "local x"
print(x) #prints "global x"</lang>
print(x) #prints "global x"</syntaxhighlight>


attach() will attach an environment or data set to the chain of
attach() will attach an environment or data set to the chain of
enclosing environments.
enclosing environments.


<lang R>d <- data.frame(a=c(2,4,6), b = c(5,7,9))
<syntaxhighlight lang="r">d <- data.frame(a=c(2,4,6), b = c(5,7,9))
attach(d)
attach(d)
b - a #success
b - a #success
detach(d)
detach(d)
b - a #produces error</lang>
b - a #produces error</syntaxhighlight>


Assignment using <- or -> by default happens in the local
Assignment using <- or -> by default happens in the local
Line 1,363: Line 1,363:
definition is found.
definition is found.


<lang R>x <- "global x"
<syntaxhighlight lang="r">x <- "global x"
print(x) #"global x"
print(x) #"global x"


Line 1,399: Line 1,399:
})
})
print(x) #"twice modified global x"
print(x) #"twice modified global x"
print(y) #"modified global y"</lang>
print(y) #"modified global y"</syntaxhighlight>


However, the scope and other aspects of evaluation can be
However, the scope and other aspects of evaluation can be
Line 1,408: Line 1,408:
function.
function.


<lang R>x <- "global x"
<syntaxhighlight lang="r">x <- "global x"
f <- function() {
f <- function() {
cat("Lexically enclosed x: ", x,"\n")
cat("Lexically enclosed x: ", x,"\n")
Line 1,418: Line 1,418:
x <- "local x"
x <- "local x"
f()
f()
})</lang>
})</syntaxhighlight>


A function's arguments are not evaluated until needed; the function
A function's arguments are not evaluated until needed; the function
Line 1,426: Line 1,426:
defined by its first argument, enclosed within the current scope.
defined by its first argument, enclosed within the current scope.


<lang R>d <- data.frame(a=c(2,4,6), b = c(5,7,9))
<syntaxhighlight lang="r">d <- data.frame(a=c(2,4,6), b = c(5,7,9))
also <- c(1, 0, 2)
also <- c(1, 0, 2)
with(d, mean(b - a + also)) #returns 4
with(d, mean(b - a + also)) #returns 4
Line 1,437: Line 1,437:
eval(substitute(expr), envir=env)
eval(substitute(expr), envir=env)
}
}
with.impl(d, mean(b - a + also))</lang>
with.impl(d, mean(b - a + also))</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 1,447: Line 1,447:
(formerly Perl 6)
(formerly Perl 6)
Raku has a system of declarators that introduce new names into various scopes.
Raku has a system of declarators that introduce new names into various scopes.
<lang perl6>my $lexical-variable;
<syntaxhighlight lang="raku" line>my $lexical-variable;
our $package-variable;
our $package-variable;
state $persistent-lexical;
state $persistent-lexical;
has $.public-attribute;</lang>
has $.public-attribute;</syntaxhighlight>
Lexically scoped variables, declared with <tt>my</tt>, are the norm.
Lexically scoped variables, declared with <tt>my</tt>, are the norm.
Function definitions are intrinsically lexical by default, but allow for forward references, unlike any other declaration.
Function definitions are intrinsically lexical by default, but allow for forward references, unlike any other declaration.
Line 1,462: Line 1,462:


In Perl 5, dynamic scoping is done via "local" to temporarily change the value of a global variable. This mechanism is still specced for Raku, albeit with a different keyword, <tt>temp</tt>, that better reflects what it's doing. None of the implementations yet implement <tt>temp</tt>, since Raku does dynamic scoping via a more robust system of scanning up the call stack for the innermost dynamic declaration, which actually lives in the lexical scope of the function declaring it. We distinguish dynamic variables syntactically by introducing a "twigil" after the sigil. The twigil for dynamic variables is <tt>*</tt> to represent that we don't know how to qualify the location of the variable.
In Perl 5, dynamic scoping is done via "local" to temporarily change the value of a global variable. This mechanism is still specced for Raku, albeit with a different keyword, <tt>temp</tt>, that better reflects what it's doing. None of the implementations yet implement <tt>temp</tt>, since Raku does dynamic scoping via a more robust system of scanning up the call stack for the innermost dynamic declaration, which actually lives in the lexical scope of the function declaring it. We distinguish dynamic variables syntactically by introducing a "twigil" after the sigil. The twigil for dynamic variables is <tt>*</tt> to represent that we don't know how to qualify the location of the variable.
<lang perl6>sub a {
<syntaxhighlight lang="raku" line>sub a {
my $*dyn = 'a';
my $*dyn = 'a';
c();
c();
Line 1,474: Line 1,474:
}
}
a(); # says a
a(); # says a
b(); # says b</lang>
b(); # says b</syntaxhighlight>
The standard IO filehandles are dynamic variables $*IN, $*OUT, and $*ERR, which allows a program to easily redirect the input or output from any subroutine and all its children. More generally, since most process-wide variables are accessed via this mechanism, and only look in the PROCESS package as a last resort, any chunk of code can pretend to be in a different kind of process environment merely by redefining one or more of the dynamic variables in question, such as %*ENV.
The standard IO filehandles are dynamic variables $*IN, $*OUT, and $*ERR, which allows a program to easily redirect the input or output from any subroutine and all its children. More generally, since most process-wide variables are accessed via this mechanism, and only look in the PROCESS package as a last resort, any chunk of code can pretend to be in a different kind of process environment merely by redefining one or more of the dynamic variables in question, such as %*ENV.


Line 1,493: Line 1,493:


If more than one identical label is specified, only the first label is recognized (and it isn't considered an error).
If more than one identical label is specified, only the first label is recognized (and it isn't considered an error).
<lang rexx>/*REXX program to display scope modifiers (for subroutines/functions). */
<syntaxhighlight lang="rexx">/*REXX program to display scope modifiers (for subroutines/functions). */
a=1/4
a=1/4
b=20
b=20
Line 1,515: Line 1,515:
ewe = 'female sheep'
ewe = 'female sheep'
d = 55555555
d = 55555555
return /*compliments to Jules Verne's Captain Nemo? */</lang>
return /*compliments to Jules Verne's Captain Nemo? */</syntaxhighlight>


===version 2 scope is DYNAMIC===
===version 2 scope is DYNAMIC===
<lang rexx>a=1
<syntaxhighlight lang="rexx">a=1
b=2
b=2
c=3
c=3
Line 1,534: Line 1,534:
Say 'in s sigl a b c' sigl a b c
Say 'in s sigl a b c' sigl a b c
x=4
x=4
Return </lang>
Return </syntaxhighlight>
{{out}}
{{out}}
When s is called from p, it can only see the variable b that is exposed by p.
When s is called from p, it can only see the variable b that is exposed by p.
Line 1,561: Line 1,561:
A protected method is available within a class and available to instances of the same class.<br>
A protected method is available within a class and available to instances of the same class.<br>
By default, methods are public. Use like this:
By default, methods are public. Use like this:
<lang ruby>class Demo
<syntaxhighlight lang="ruby">class Demo
#public methods here
#public methods here
Line 1,569: Line 1,569:
private
private
#private methods
#private methods
end</lang>
end</syntaxhighlight>
Ruby is an open language. Declaring methods private prevents inadvertend use of methods not meant to be used outside a class. However it is easy to circumvent with metaprogramming methods like <code>instance_eval</code>.
Ruby is an open language. Declaring methods private prevents inadvertend use of methods not meant to be used outside a class. However it is easy to circumvent with metaprogramming methods like <code>instance_eval</code>.


Line 1,579: Line 1,579:
In Tcl procedures, variables are local to the procedure unless explicitly declared otherwise (unless they contain namespace separators, which forces interpretation as namespace-scoped names). Declarations may be used to access variables in the global namespace, or the current namespace, or indeed any other namespace.
In Tcl procedures, variables are local to the procedure unless explicitly declared otherwise (unless they contain namespace separators, which forces interpretation as namespace-scoped names). Declarations may be used to access variables in the global namespace, or the current namespace, or indeed any other namespace.
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}
<lang tcl>set globalVar "This is a global variable"
<syntaxhighlight lang="tcl">set globalVar "This is a global variable"
namespace eval nsA {
namespace eval nsA {
variable varInA "This is a variable in nsA"
variable varInA "This is a variable in nsA"
Line 1,596: Line 1,596:
nsB::showOff varInA
nsB::showOff varInA
nsB::showOff varInB
nsB::showOff varInB
nsB::showOff localVar</lang>
nsB::showOff localVar</syntaxhighlight>
{{out}}
{{out}}
<pre>variable globalVar holds "This is a global variable"
<pre>variable globalVar holds "This is a global variable"
Line 1,605: Line 1,605:


{{works with|Tcl|8.6}} or {{libheader|TclOO}}
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<lang tcl>oo::class create example {
<syntaxhighlight lang="tcl">oo::class create example {
# Note that this is otherwise syntactically the same as a local variable
# Note that this is otherwise syntactically the same as a local variable
variable objVar
variable objVar
Line 1,615: Line 1,615:
}
}
}
}
[example new] showOff</lang>
[example new] showOff</syntaxhighlight>
{{out}}
{{out}}
<pre>variable objVar holds "This is an object variable"</pre>
<pre>variable objVar holds "This is an object variable"</pre>
Line 1,626: Line 1,626:


To demonstrate these capabilities, here is an example of how we can create a <code>decr</code> command that is just like the <code>incr</code> command except for working with increments in the opposite direction.
To demonstrate these capabilities, here is an example of how we can create a <code>decr</code> command that is just like the <code>incr</code> command except for working with increments in the opposite direction.
<lang tcl>proc decr {varName {decrement 1}} {
<syntaxhighlight lang="tcl">proc decr {varName {decrement 1}} {
upvar 1 $varName var
upvar 1 $varName var
incr var [expr {-$decrement}]
incr var [expr {-$decrement}]
}</lang>
}</syntaxhighlight>
Here is a kind of version of <code>eval</code> that concatenates its arguments with a semicolon first, instead of the default behavior (a space):
Here is a kind of version of <code>eval</code> that concatenates its arguments with a semicolon first, instead of the default behavior (a space):
<lang tcl>proc semival args {
<syntaxhighlight lang="tcl">proc semival args {
uplevel 1 [join $args ";"]
uplevel 1 [join $args ";"]
}</lang>
}</syntaxhighlight>
Of course, these capabilities are designed to be used together. Here is a command that will run a loop over a variable between two bounds, executing a "block" for each step.
Of course, these capabilities are designed to be used together. Here is a command that will run a loop over a variable between two bounds, executing a "block" for each step.
<lang tcl>proc loop {varName from to body} {
<syntaxhighlight lang="tcl">proc loop {varName from to body} {
upvar 1 $varName var
upvar 1 $varName var
for {set var $from} {$var <= $to} {incr var} {
for {set var $from} {$var <= $to} {incr var} {
Line 1,649: Line 1,649:
}
}
}
}
puts "done"</lang>
puts "done"</syntaxhighlight>
which prints:
which prints:
<pre>x is now 1
<pre>x is now 1
Line 1,663: Line 1,663:
The only scope modifier in TI-89 BASIC is the <code>Local</code> command, which makes the variable local to the enclosing program or function rather than global (in some folder).
The only scope modifier in TI-89 BASIC is the <code>Local</code> command, which makes the variable local to the enclosing program or function rather than global (in some folder).


<lang ti89b>Local x
<syntaxhighlight lang="ti89b">Local x
2 → x
2 → x
Return x^x</lang>
Return x^x</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==
Line 1,674: Line 1,674:
Illustration using named blocks. In the first example, the block succeeds and so its binding passes on:
Illustration using named blocks. In the first example, the block succeeds and so its binding passes on:


<lang txr>@(maybe)@# perhaps this subclause suceeds or not
<syntaxhighlight lang="txr">@(maybe)@# perhaps this subclause suceeds or not
@ (block foo)
@ (block foo)
@ (bind a "a")
@ (bind a "a")
@ (accept foo)
@ (accept foo)
@(end)
@(end)
@(bind b "b")</lang>
@(bind b "b")</syntaxhighlight>


Result (with <code>-B</code> option to dump bindings):
Result (with <code>-B</code> option to dump bindings):
Line 1,688: Line 1,688:
By contrast, in this version, the block fails. Because it is contained in a <code>@(maybe)</code>, evaluation can proceed, but the binding for <code>a</code> is gone.
By contrast, in this version, the block fails. Because it is contained in a <code>@(maybe)</code>, evaluation can proceed, but the binding for <code>a</code> is gone.


<lang txr>@(maybe)@# perhaps this subclause suceeds or not
<syntaxhighlight lang="txr">@(maybe)@# perhaps this subclause suceeds or not
@ (block foo)
@ (block foo)
@ (bind a "a")
@ (bind a "a")
@ (fail foo)
@ (fail foo)
@(end)
@(end)
@(bind b "b")</lang>
@(bind b "b")</syntaxhighlight>


Result (with <code>-B</code>):
Result (with <code>-B</code>):
Line 1,707: Line 1,707:
be switched on and off throughout a source text, and only the symbols
be switched on and off throughout a source text, and only the symbols
declared when they're on will become visible library entry points.
declared when they're on will become visible library entry points.
<lang Ursala>local_shop = 0
<syntaxhighlight lang="ursala">local_shop = 0
hidden_variable = 3
hidden_variable = 3


Line 1,717: Line 1,717:
#library-
#library-


for_local_people = 7</lang>
for_local_people = 7</syntaxhighlight>
By default, every symbol is visible to every other within the same
By default, every symbol is visible to every other within the same
file, and multiple declarations of the same symbol are an error, but the
file, and multiple declarations of the same symbol are an error, but the
Line 1,723: Line 1,723:
scopes within a single file. In this example, the symbol <code>x</code> will have
scopes within a single file. In this example, the symbol <code>x</code> will have
a value of 1,
a value of 1,
<lang Ursala>foo = 1
<syntaxhighlight lang="ursala">foo = 1


#hide+
#hide+
Line 1,732: Line 1,732:
#hide-
#hide-


x = foo</lang>
x = foo</syntaxhighlight>
but it will be 2 in this example, where
but it will be 2 in this example, where
the <code>#export</code> directive selectively allows an otherwise
the <code>#export</code> directive selectively allows an otherwise
hidden declaration to be visible outside its enclosing
hidden declaration to be visible outside its enclosing
scope, and allows name clashes to be resolved by proximity.
scope, and allows name clashes to be resolved by proximity.
<lang Ursala>foo = 1
<syntaxhighlight lang="ursala">foo = 1


#hide+
#hide+
Line 1,749: Line 1,749:
#hide-
#hide-


x = foo</lang>
x = foo</syntaxhighlight>
The <code>#hide</code> directives can be arbitrarily nested in matched pairs
The <code>#hide</code> directives can be arbitrarily nested in matched pairs
to create block structured scope, but doing so is likely to be
to create block structured scope, but doing so is likely to be
Line 1,758: Line 1,758:
declaration. However, this behavior can be overridden using
declaration. However, this behavior can be overridden using
the dash operator as shown.
the dash operator as shown.
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std


cat = 3
cat = 3
a_string = std-cat('foo','bar')</lang>
a_string = std-cat('foo','bar')</syntaxhighlight>
Here, <code>std-cat</code> refers to the concatenation function from the standard
Here, <code>std-cat</code> refers to the concatenation function from the standard
library, not the locally declared constant by that name.
library, not the locally declared constant by that name.
Line 1,771: Line 1,771:


In the following example, the attempt to access the private field is picked up at compile time (Wren has a single-pass 'bytecode' compiler) and so the penultimate line, although OK, doesn't print.
In the following example, the attempt to access the private field is picked up at compile time (Wren has a single-pass 'bytecode' compiler) and so the penultimate line, although OK, doesn't print.
<lang ecmascript>class MyClass {
<syntaxhighlight lang="ecmascript">class MyClass {
construct new(a) {
construct new(a) {
_a = a // creates an instance field _a automatically
_a = a // creates an instance field _a automatically
Line 1,780: Line 1,780:
var mc = MyClass.new(3)
var mc = MyClass.new(3)
System.print(mc.a) // fine
System.print(mc.a) // fine
System.print(mc._a) // can't access _a directly as its private to the class</lang>
System.print(mc._a) // can't access _a directly as its private to the class</syntaxhighlight>


{{out}}
{{out}}