Scope modifiers: Difference between revisions

→‎Tcl: Added implementation
(Add Python 3.x)
(→‎Tcl: Added implementation)
Line 115:
>>> </lang>
More information on the scope modifiers can be found [http://docs.python.org/3.0/reference/simple_stmts.html#grammar-token-global_stmt here].<br>
 
=={{header|Tcl}}==
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}}
<lang tcl>set globalVar "This is a global variable"
namespace eval nsA {
variable varInA "This is a variable in nsA"
}
namespace eval nsB {
variable varInB "This is a variable in nsB"
proc showOff {varname} {
set localVar "This is a local variable"
global globalVar
variable varInB
namespace upvar ::nsA varInA varInA
puts "variable $varname holds \"[set $varname]\""
}
}
nsB::showOff globalVar
nsB::showOff varInA
nsB::showOff varInB
nsB::showOff localVar</lang>
Output:
<pre>variable globalVar holds "This is a global variable"
variable varInA holds "This is a variable in nsA"
variable varInB holds "This is a variable in nsB"
variable localVar holds "This is a local variable"</pre>
Objects have an extra variable access mode. All the variables declared in a class definition are visible by default in the methods defined in that class. All other variable access modes are still available too.
 
{{works with|Tcl|8.6}}
<lang tcl>oo::class create example {
# Note that this is otherwise syntactically the same as a local variable
variable objVar
constructor {} {
set objVar "This is an object variable"
}
method showOff {} {
puts "variable objVar holds \"$objVar\""
}
}
[example new] showOff</lang>Output:<pre>variable objVar holds "This is an object variable"</pre>
Anonymous user