Scope modifiers: Difference between revisions

m
m (→‎{{header|Raku}}: Fix comments: Perl 6 --> Raku)
m (→‎{{header|Wren}}: Minor tidy)
 
(13 intermediate revisions by 10 users not shown)
Line 7:
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V x = ‘From global scope’
 
F outerfunc()
V x = ‘From scope at outerfunc’
 
F scoped_local()
V x = ‘scope local’
R ‘scoped_local scope gives x = ’x
print(scoped_local())
 
F scoped_nonlocal()
R ‘scoped_nonlocal scope gives x = ’@x
print(scoped_nonlocal())
 
F scoped_global()
R ‘scoped_global scope gives x = ’:x
print(scoped_global())
 
outerfunc()</syntaxhighlight>
 
{{out}}
<pre>
scoped_local scope gives x = scope local
scoped_nonlocal scope gives x = From scope at outerfunc
scoped_global scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From scope at outerfunc
</pre>
 
=={{header|6502 Assembly}}==
Like most assembly languages, 6502 has no concept of scope. Scope can be enforced by the assembler itself. While this may seem like a bad thing, since scope is by definition a limitation on variables the programmer can access, an assembler that implements scope can allow the programmer to reuse labels (which would otherwise have to be unique throughout the entire program).
 
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:
<syntaxhighlight lang="6502asm">macro LDIR,source,dest,count
;LoaD, Increment, Repeat
lda #<source
sta $00
lda #>source
sta $01
 
lda #<dest
sta $02
lda #>dest
sta $03
 
ldx count
ldy #0
\@: ;this is a local label
 
lda ($00),y ;load a byte from the source address
sta ($02),y ;store in destination address
iny ;increment
dex
bne \@ ;repeat until x=0
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.)
 
=={{header|68000 Assembly}}==
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.
 
<syntaxhighlight lang="68000devpac">foo:
MOVE.L #$DEADBEEF,D0
MOVE.L #$16-1,D1
.bar:
DBRA D1,.bar ;any code outside "foo" cannot JMP, Bxx, BRA, or JSR/BSR here by using the name ".bar"
RTS</syntaxhighlight>
 
=={{header|Ada}}==
Line 12 ⟶ 83:
In [[Ada]] declarative region of a package has publicly visible and private parts.
The private part is introduced by '''private''':
<langsyntaxhighlight lang="ada">package P is
... -- Declarations placed here are publicly visible
private
... -- These declarations are visible only to the children of P
end P;</langsyntaxhighlight>
Correspondingly a type or object declaration may be incomplete in the public part providing an official interface. For example:
<langsyntaxhighlight lang="ada">package P is
type T is private; -- No components visible
procedure F (X : in out T); -- The only visible operation
Line 28 ⟶ 99:
procedure V (X : in out T); -- Operation used only by children
N : constant T := (Component => 0); -- Constant implementation
end P;</langsyntaxhighlight>
 
===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:
<langsyntaxhighlight lang="ada">package body P is
-- The implementation of P, invisible to anybody
procedure W (X : in out T); -- Operation used only internally
end P;</langsyntaxhighlight>
===Private children===
The keyword '''private''' can be applied to the whole package, a child of another package:
<langsyntaxhighlight lang="ada">private package P.Q is
... -- Visible to the siblings only
private
... -- Visible to the children only
end P.Q;</langsyntaxhighlight>
This package can be then used only by private siblings of the same parent P.
 
Line 56 ⟶ 127:
=={{header|AutoHotkey}}==
{{AutoHotkey case}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">singleton = "global variable"
 
assume_global()
Line 80 ⟶ 151:
_%member% := ""
Return (_%member%)
}</langsyntaxhighlight>
 
=={{header|Axe}}==
Line 88 ⟶ 159:
==={{header|Applesoft BASIC}}===
All variables are global by default, except the parameter which is local to the function. There are no scope modifiers.
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic"> 10 X = 1
20 DEF FN F(X) = X
30 DEF FN G(N) = X
40 PRINT FN F(2)
50 PRINT FN G(3)</langsyntaxhighlight>
{{out}}
<pre>2
Line 105 ⟶ 176:
 
The scope modifier PRIVATE declares a variable static to a function; it sets the value to zero/NULL initially.
<langsyntaxhighlight lang="bbcbasic"> var1$ = "Global1"
var2$ = "Global2"
Line 137 ⟶ 208:
PRINT "var2$ = """ var2$ """"
ENDPROC</langsyntaxhighlight>
{{out}}
<pre>
Line 171 ⟶ 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.
 
<langsyntaxhighlight lang="bc">define g(a) {
auto b
Line 210 ⟶ 281:
"Global scope (before call): b = "; b
"Global scope (before call): c = "; c
"Global scope (before call): d = "; d</langsyntaxhighlight>
 
{{Out}}
Line 237 ⟶ 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.
 
<langsyntaxhighlight lang="bracmat"> 67:?x {x has global scope}
& 77:?y { y has global scope }
& ( double
Line 249 ⟶ 320:
& double$
& !x+!y
)</langsyntaxhighlight>
 
"Variables" in lambda expressions have lexical scope. But can of course not be varied.
 
<langsyntaxhighlight lang="bracmat">/('(x./('(y.$x+$y))$3))$5 { x and y have lexical scope }</langsyntaxhighlight>
 
=={{header|C}}==
Line 259 ⟶ 330:
 
'''file1.c'''
<langsyntaxhighlight lang="c">int a; // a is global
static int p; // p is "locale" and can be seen only from file1.c
 
Line 282 ⟶ 353:
v = v * 1.02; // update global v
// ...
}</langsyntaxhighlight>
 
'''file2.c'''
<langsyntaxhighlight 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
// in file1.c
Line 292 ⟶ 363:
// normally these things go into a header.h
 
// ...</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">public //visible to anything.
protected //visible to current class and to derived classes.
internal //visible to anything inside the same assembly (.dll/.exe).
Line 312 ⟶ 383:
//private | Yes | No | No || No | No
// C# 7.2:
//private protected | Yes | Yes | No || No | No</langsyntaxhighlight>
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.
Line 318 ⟶ 389:
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:
<langsyntaxhighlight lang="csharp">public interface IPrinter
{
void Print();
Line 339 ⟶ 410:
}
}
</syntaxhighlight>
</lang>
Other declarations follow lexical scoping.<br/>
Visibility is determined by the enclosing braces { }<br/>
Line 361 ⟶ 432:
The next example declaims that <code>*bug*</code> has dynamic scope. Meanwhile, <code>shape</code> has lexical scope.
 
<langsyntaxhighlight lang="lisp">;; *bug* shall have a dynamic binding.
(declaim (special *bug*))
 
Line 372 ⟶ 443:
(let ((shape "circle") (*bug* "cockroach"))
(format t "~%Put ~A in your ~A..." *bug* shape)
(speak))))</langsyntaxhighlight>
 
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 384 ⟶ 455:
 
=={{header|Delphi}}==
<syntaxhighlight lang Delphi="delphi">private</langsyntaxhighlight>
Can only be seen inside declared class.
 
<syntaxhighlight lang Delphi="delphi">protected</langsyntaxhighlight>
Can be seen in descendent classes.
 
<syntaxhighlight lang Delphi="delphi">public</langsyntaxhighlight>
Can be seen from outside the class.
 
<syntaxhighlight lang Delphi="delphi">protected</langsyntaxhighlight>
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.
 
<syntaxhighlight lang Delphi="delphi">automated</langsyntaxhighlight>
Same visibility as Public, and used for Automation Objects. This is currently only maintained for backward compatibility.
 
<langsyntaxhighlight Delphilang="delphi">strict private
strict protected</langsyntaxhighlight>
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}}==
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.
<langsyntaxhighlight lang="dejavu">set :a "global"
if true:
!print a
Line 412 ⟶ 483:
!print getglobal :a
!print a
</syntaxhighlight>
</lang>
{{out}}
<pre>global
Line 434 ⟶ 505:
* a global variable
 
<langsyntaxhighlight Eiffellang="eiffel">feature
some_procedure(int: INTEGER; char: CHARACTER)
local
Line 454 ⟶ 525:
end
 
-- s, some_procedure and some_function have scope here</langsyntaxhighlight>
 
=={{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:
 
<langsyntaxhighlight lang="ela">pi # private
pi = 3.14159
 
sum # private
sum x y = x + y</langsyntaxhighlight>
 
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 469 ⟶ 540:
=={{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.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( a_module ).
 
Line 479 ⟶ 550:
 
add( N, N ) -> N + N.
</syntaxhighlight>
</lang>
 
{{out}}
Line 488 ⟶ 559:
** exception error: undefined function a_module:add/2
</pre>
 
=={{header|FreeBASIC}}==
* Functions must be defined before being used and are always global in scope.
 
* Variables must be defined before being used.
 
* 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.
<syntaxhighlight lang="freebasic">'Declares a integer variable and reserves memory to accommodate it
Dim As Integer baseAge = 10
'Define a variable that has static storage
Static As String person
person = "Amy"
'Declare variables that are both accessible inside and outside procedures
Dim Shared As String friend
friend = "Susan"
Dim Shared As Integer ageDiff = 3
Dim Shared As Integer extraYears = 5
 
Sub test()
'Declares a integer variable and reserves memory to accommodate it
Dim As Integer baseAge = 30
'Define a variable that has static storage
Static As String person
person = "Bob"
'Declare a local variable distinct from a variable with global scope having the same name
Static As Integer extraYears = 2
Print person; " and "; friend; " are"; baseAge; " and"; baseAge + ageDiff + extraYears; " years old."
End Sub
 
test()
Print person; " and "; friend; " are"; baseAge; " and"; baseAge + ageDiff + extraYears; " years old."
Sleep</syntaxhighlight>
{{out}}
<pre>Bob and Susan are 30 and 35 years old.
Amy and Susan are 10 and 18 years old.</pre>
 
=={{header|Free Pascal}}==
Line 517 ⟶ 624:
=={{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.
<langsyntaxhighlight Iconlang="icon">global var1 # used outside of procedures
 
procedure one() # a global procedure (the only kind)
local var2 # used inside of procedures
static var3 # also used inside of procedures
end</langsyntaxhighlight>
 
Co-expressions (both languages) also redefine scope - any local variables referenced
Line 533 ⟶ 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:
 
<langsyntaxhighlight Jlang="j"> A=: 1
B=: 2
C=: 3
Line 549 ⟶ 656:
2
D
|value error</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="java">public //any class may access this member directly
 
protected //only this class, subclasses of this class,
Line 588 ⟶ 695:
}
//can use x and y here, but NOT z
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 596 ⟶ 703:
 
A named function definition (<code>function foo() { ... }</code>) is “hoisted” to the top of the enclosing function; it is therefore possible to call a function before its definition would seem to be executed.
 
=={{header|jq}}==
 
jq uses lexical scoping.
 
Variables defined on the command-line have global scope
but are hidden by the rules of lexical scoping.
 
Local scope is introduced by function declarations (including declarations of inner functions)
and by variable assignments, i.e. by `def` and `as` statements.
 
Example:
<pre>
jq -nc --arg x a '
def a($x):
def b($x): 1 as $x | $x;
$x, b(10)];
 
[$x, a(0)]'
</pre>
{{Output}}
<pre>
["a",[0,1]]
</pre>
 
=={{header|Julia}}==
Line 602 ⟶ 733:
<code> local x </code>introduces a new local variable x.
<br /><br />
<langsyntaxhighlight lang="julia">
julia> function foo(n)
x = 0
Line 615 ⟶ 746:
julia> foo(10)
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.
 
Line 630 ⟶ 761:
 
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:
<langsyntaxhighlight lang="scala">// version 1.1.2
 
class SomeClass {
Line 651 ⟶ 782:
println(sc2.id)
println(SomeClass.objectsCreated)
}</langsyntaxhighlight>
 
{{out}}
Line 677 ⟶ 808:
=={{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.
<langsyntaxhighlight lang="logo">
make "g 5 ; global
 
Line 693 ⟶ 824:
localmake "h 5 ; hides global :h within this procedure and those it calls
end
</syntaxhighlight>
</lang>
 
=={{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).
<langsyntaxhighlight lang="logtalk">
:- public(foo/1). % predicate can be called from anywhere
 
Line 712 ⟶ 843:
:- protocol(extended, % no change to the scope of the predicates inherited from the extended protocol
extends(public::minimal)).
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
In Lua, variables are global by default, but can be modified to be local to the block in which they are declared.
<syntaxhighlight lang="lua">foo = "global" -- global scope
print(foo)
local foo = "local module" -- local to the current block (which is the module)
print(foo) -- local obscures the global
print(_G.foo) -- but global still exists
do -- create a new block
print(foo) -- outer module-level scope still visible
local foo = "local block" -- local to the current block (which is this "do")
print(foo) -- obscures outer module-level local
for foo = 1,2 do -- create another more-inner scope
print("local for "..foo) -- obscures prior block-level local
end -- and close the scope
print(foo) -- prior block-level local still exists
end -- close the block (and thus its scope)
print(foo) -- module-level local still exists
print(_G.foo) -- global still exists</syntaxhighlight>
{{out}}
<pre>global
local module
global
local module
local block
local for 1
local for 2
local block
local module
global</pre>
 
=={{header|M2000 Interpreter}}==
Line 727 ⟶ 888:
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 {
M=1000
Line 805 ⟶ 966:
Modules ? ' list of modules show two: A and A.Checkit
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).
 
Line 812 ⟶ 973:
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 CheckSub {
Line 867 ⟶ 1,028:
}
Call Alfa
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Module -> localize names of variables (lexical scoping)
Block -> localize values of variables (dynamic scoping)
 
Module creates new symbols:
 
Module[{x}, Print[x];
Module[{x}, Print[x]]
]
 
->x$119
->x$120
 
Block localizes values only; it does not create new symbols:
 
x = 7;
Block[{x=0}, Print[x]]
Print[x]
->0
->7</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight MUMPSlang="mumps">OUTER
SET OUT=1,IN=0
WRITE "OUT = ",OUT,!
Line 906 ⟶ 1,062:
WRITE "IN (inner scope) = ",IN,!
KILL OUT
QUIT</langsyntaxhighlight>
Execution:<pre>
USER>D ^SCOPE
Line 918 ⟶ 1,074:
=={{header|Nim}}==
Identifiers annotated with a <code>*</code> are accessible from other modules
<langsyntaxhighlight lang="nim">proc foo = echo "foo" # hidden
proc bar* = echo "bar" # acessible
 
type MyObject = object
name*: string # accessible
secretAge: int # hidden</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 932 ⟶ 1,088:
Pascal does not have scope modifiers.
Regular block scopes are defined simply by virtue of the declaration’s position:
<langsyntaxhighlight lang="pascal">procedure super;
var
f: boolean;
Line 959 ⟶ 1,115:
begin
// here, `c`, `f`, and `x`, as well as,
// `nestedProcedure`, `commonTask`, `fooBar` and `fooBarsuper` are available
end;</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 969 ⟶ 1,125:
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.
 
<langsyntaxhighlight lang="perl">use strict;
$x = 1; # Compilation error.
our $y = 2;
Line 977 ⟶ 1,133:
our $z = 3;
package Bar;
print "$z\n"; # Refers to $Foo::z.</langsyntaxhighlight>
 
<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.
 
<langsyntaxhighlight lang="perl">package Foo;
my $fruit = 'apple';
package Bar;
Line 993 ⟶ 1,149:
our $fruit = 'orange';
print "$fruit\n"; # Prints "orange"; refers to $Bar::fruit.
# The first $fruit is inaccessible.</langsyntaxhighlight>
 
<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.
 
<langsyntaxhighlight lang="perl">use 5.10.0;
 
sub count_up
Line 1,006 ⟶ 1,162:
 
count_up; # Prints "13".
count_up; # Prints "14".</langsyntaxhighlight>
 
<code>local</code> gives a package variable a new value for the duration of the current ''dynamic'' scope.
 
<langsyntaxhighlight lang="perl">our $camelid = 'llama';
 
sub phooey
Line 1,026 ⟶ 1,182:
 
do_phooey; # Prints "alpaca".
phooey; # Prints "llama".</langsyntaxhighlight>
 
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.
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
Identifiers are private (restricted to a single file) by default, or they can be made global by prefixing the
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 only). 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), egetc.
<lang Phix>forward function localf() -- not normally necesssary, but will not harm
forward global function globalf() -- ""
 
<!--<syntaxhighlight lang="phix">-->
function localf()
<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>
return 1
<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>
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">localf</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</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: #008080;">return</span> <span style="color: #000000;">2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</syntaxhighlight>-->
 
global function globalf()
return 2
end function</lang>
Here, localf() can only be invoked from within the same file, but globalf() can be invoked from any other file
that (directly or indirectly) includes it. The global keyword is equally applicable to routines, variables, and constants.
Line 1,049 ⟶ 1,209:
 
Namespaces for specific (entire) files can be used to qualify global identifiers, should there be a name clash between several files.
<lang Phix>include somefile.e as xxx
-- alternatively, within somefile.e:
namespace xxx -- (only supported in Phix for compatibility with OpenEuphoria)
 
<!--<syntaxhighlight lang="phix">-->
res = xxx:globalf() -- call a global function named globalf, specifically the one declared in somefile.e</lang>
<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: #7060A8;">namespace</span> <span style="color: #000000;">xxx</span> <span style="color: #000080;font-style:italic;">-- (only supported in Phix for compatibility with OpenEuphoria)</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>
<!--</syntaxhighlight>-->
 
Note however that one of the main reasons for namespaces is to avoid having to amend any included (3rd party)
files, so having namespaces within the file itself may prove to be less than helpful, should they (the namespaces
Line 1,061 ⟶ 1,225:
in and out of scope in every single source file throughout the application. What this means is that if file
a includes b includes c, you can refer in a to c via the namespace of b, but not directly, unless you also
explicitly include c in a. (Obviously were something in c globally unique you could refer to it without any namespace.)
 
The compiler maintains a list of files it has processed; re-inclusion (by some other file) just adds any
Line 1,099 ⟶ 1,263:
=={{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:
<langsyntaxhighlight lang="powershell">$a = "foo" # global scope
function test {
$a = "bar" # local scope
Write-Host Local: $a # "bar" - local variable
Write-Host Global: $global:a # "foo" - global variable
}</langsyntaxhighlight>
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,115 ⟶ 1,279:
 
* 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.
<langsyntaxhighlight PureBasiclang="purebasic">;define a local integer variable by simply using it
baseAge.i = 10
;explicitly define local strings
Line 1,146 ⟶ 1,310:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>Bob and Susan are 30 and 35 years old.
Line 1,159 ⟶ 1,323:
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:
 
<langsyntaxhighlight lang="python">>>> x="From global scope"
>>> def outerfunc():
x = "From scope at outerfunc"
Line 1,188 ⟶ 1,352:
scoped_global scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From global scope
>>></langsyntaxhighlight>
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,200 ⟶ 1,364:
up the chain of parent environments.
 
<langsyntaxhighlight Rlang="r">X <- "global x"
f <- function() {
x <- "local x"
Line 1,206 ⟶ 1,370:
}
f() #prints "local x"
print(x) #prints "global x"</langsyntaxhighlight>
 
attach() will attach an environment or data set to the chain of
enclosing environments.
 
<langsyntaxhighlight Rlang="r">d <- data.frame(a=c(2,4,6), b = c(5,7,9))
attach(d)
b - a #success
detach(d)
b - a #produces error</langsyntaxhighlight>
 
Assignment using <- or -> by default happens in the local
Line 1,223 ⟶ 1,387:
definition is found.
 
<langsyntaxhighlight Rlang="r">x <- "global x"
print(x) #"global x"
 
Line 1,259 ⟶ 1,423:
})
print(x) #"twice modified global x"
print(y) #"modified global y"</langsyntaxhighlight>
 
However, the scope and other aspects of evaluation can be
Line 1,268 ⟶ 1,432:
function.
 
<langsyntaxhighlight Rlang="r">x <- "global x"
f <- function() {
cat("Lexically enclosed x: ", x,"\n")
Line 1,278 ⟶ 1,442:
x <- "local x"
f()
})</langsyntaxhighlight>
 
A function's arguments are not evaluated until needed; the function
Line 1,286 ⟶ 1,450:
defined by its first argument, enclosed within the current scope.
 
<langsyntaxhighlight Rlang="r">d <- data.frame(a=c(2,4,6), b = c(5,7,9))
also <- c(1, 0, 2)
with(d, mean(b - a + also)) #returns 4
Line 1,297 ⟶ 1,461:
eval(substitute(expr), envir=env)
}
with.impl(d, mean(b - a + also))</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,307 ⟶ 1,471:
(formerly Perl 6)
Raku has a system of declarators that introduce new names into various scopes.
<syntaxhighlight lang="raku" perl6line>my $lexical-variable;
our $package-variable;
state $persistent-lexical;
has $.public-attribute;</langsyntaxhighlight>
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.
Line 1,322 ⟶ 1,486:
 
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.
<syntaxhighlight lang="raku" perl6line>sub a {
my $*dyn = 'a';
c();
Line 1,334 ⟶ 1,498:
}
a(); # says a
b(); # says b</langsyntaxhighlight>
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,353 ⟶ 1,517:
 
If more than one identical label is specified, only the first label is recognized (and it isn't considered an error).
<langsyntaxhighlight lang="rexx">/*REXX program to display scope modifiers (for subroutines/functions). */
a=1/4
b=20
Line 1,375 ⟶ 1,539:
ewe = 'female sheep'
d = 55555555
return /*compliments to Jules Verne's Captain Nemo? */</langsyntaxhighlight>
 
===version 2 scope is DYNAMIC===
<langsyntaxhighlight lang="rexx">a=1
b=2
c=3
Line 1,394 ⟶ 1,558:
Say 'in s sigl a b c' sigl a b c
x=4
Return </langsyntaxhighlight>
{{out}}
When s is called from p, it can only see the variable b that is exposed by p.
Line 1,421 ⟶ 1,585:
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:
<langsyntaxhighlight lang="ruby">class Demo
#public methods here
Line 1,429 ⟶ 1,593:
private
#private methods
end</langsyntaxhighlight>
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,439 ⟶ 1,603:
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}}
<langsyntaxhighlight lang="tcl">set globalVar "This is a global variable"
namespace eval nsA {
variable varInA "This is a variable in nsA"
Line 1,456 ⟶ 1,620:
nsB::showOff varInA
nsB::showOff varInB
nsB::showOff localVar</langsyntaxhighlight>
{{out}}
<pre>variable globalVar holds "This is a global variable"
Line 1,465 ⟶ 1,629:
 
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<langsyntaxhighlight lang="tcl">oo::class create example {
# Note that this is otherwise syntactically the same as a local variable
variable objVar
Line 1,475 ⟶ 1,639:
}
}
[example new] showOff</langsyntaxhighlight>
{{out}}
<pre>variable objVar holds "This is an object variable"</pre>
Line 1,486 ⟶ 1,650:
 
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.
<langsyntaxhighlight lang="tcl">proc decr {varName {decrement 1}} {
upvar 1 $varName var
incr var [expr {-$decrement}]
}</langsyntaxhighlight>
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):
<langsyntaxhighlight lang="tcl">proc semival args {
uplevel 1 [join $args ";"]
}</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="tcl">proc loop {varName from to body} {
upvar 1 $varName var
for {set var $from} {$var <= $to} {incr var} {
Line 1,509 ⟶ 1,673:
}
}
puts "done"</langsyntaxhighlight>
which prints:
<pre>x is now 1
Line 1,523 ⟶ 1,687:
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).
 
<langsyntaxhighlight lang="ti89b">Local x
2 → x
Return x^x</langsyntaxhighlight>
 
=={{header|TXR}}==
Line 1,534 ⟶ 1,698:
Illustration using named blocks. In the first example, the block succeeds and so its binding passes on:
 
<langsyntaxhighlight lang="txr">@(maybe)@# perhaps this subclause suceeds or not
@ (block foo)
@ (bind a "a")
@ (accept foo)
@(end)
@(bind b "b")</langsyntaxhighlight>
 
Result (with <code>-B</code> option to dump bindings):
Line 1,548 ⟶ 1,712:
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.
 
<langsyntaxhighlight lang="txr">@(maybe)@# perhaps this subclause suceeds or not
@ (block foo)
@ (bind a "a")
@ (fail foo)
@(end)
@(bind b "b")</langsyntaxhighlight>
 
Result (with <code>-B</code>):
Line 1,567 ⟶ 1,731:
be switched on and off throughout a source text, and only the symbols
declared when they're on will become visible library entry points.
<langsyntaxhighlight Ursalalang="ursala">local_shop = 0
hidden_variable = 3
 
Line 1,577 ⟶ 1,741:
#library-
 
for_local_people = 7</langsyntaxhighlight>
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
Line 1,583 ⟶ 1,747:
scopes within a single file. In this example, the symbol <code>x</code> will have
a value of 1,
<langsyntaxhighlight Ursalalang="ursala">foo = 1
 
#hide+
Line 1,592 ⟶ 1,756:
#hide-
 
x = foo</langsyntaxhighlight>
but it will be 2 in this example, where
the <code>#export</code> directive selectively allows an otherwise
hidden declaration to be visible outside its enclosing
scope, and allows name clashes to be resolved by proximity.
<langsyntaxhighlight Ursalalang="ursala">foo = 1
 
#hide+
Line 1,609 ⟶ 1,773:
#hide-
 
x = foo</langsyntaxhighlight>
The <code>#hide</code> directives can be arbitrarily nested in matched pairs
to create block structured scope, but doing so is likely to be
Line 1,618 ⟶ 1,782:
declaration. However, this behavior can be overridden using
the dash operator as shown.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
cat = 3
a_string = std-cat('foo','bar')</langsyntaxhighlight>
Here, <code>std-cat</code> refers to the concatenation function from the standard
library, not the locally declared constant by that name.
 
=={{header|Wren}}==
Wren uses lexical scoping and has no scope modifiers as such.
 
However, instance and static fields of a class always begin respectively with one underscore or two underscores (nothing else can) and are always private to the class.
 
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.
<syntaxhighlight lang="wren">class MyClass {
construct new(a) {
_a = a // creates an instance field _a automatically
}
a { _a } // allow public access to the field
}
 
var mc = MyClass.new(3)
System.print(mc.a) // fine
System.print(mc._a) // can't access _a directly as its private to the class</syntaxhighlight>
 
{{out}}
<pre>
$ wren Scope_modifiers.wren
[./Scope_modifiers line 10] Error at '_a': Expect method name after '.'.
</pre>
 
=={{header|zkl}}==
9,483

edits