Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using a variable in a function 1

Status
Not open for further replies.

Frink

Programmer
Mar 16, 2001
798
GB
Hallo,

Why can't a function change a variable defined in the calling script?
[tt]
$scriptvar=2
function scopetest
{
"scopetest before $scriptvar"
$scriptvar=$scriptvar+1
"scopetest after $scriptvar"
}
"Before $scriptvar"
scopetest
"After $scriptvar"
[/tt]
Gives:
[tt]
Before 2
scopetest before 2
scopetest after 3
After 2
[/tt]
The results show that a copy of the variable was updated within the function, not the actual variable.
I would have expected
[tt]
Actual 3
[/tt]

Any ideas/explanation,

-Frink
 
The $scriptvar within the functions scope is private; it is unaware of the $scriptvar outside. Either the variable needs to be defined in the global scope
Code:
$[b]Global:[/b]scriptvar = 2

or the variable needs to be passed to the function and then return (this option is desirable)
Code:
function scopetest([b][int] $var[/b])
{
   $var = $var + 1
   [b]return $var[/b]
}

$scriptvar = 2
scopetest($scriptvar)

# Output is 3

-Geates
 
Cheers Geates,

Have you tried it with $global:scriptvar=2?
I did and it produced the same results.

Your second method isn't suitable for my purposes as I will have lots of script-level variables.

- Frink
 
If you're going to access variables that are outside the scope of the function, you have to include the scope qualifier even within the function. Unlike with some languages, declaring a variable to be "Global" doesn't automatically mean assignments to that variable will access the Global scope.

Try this:
Code:
$Global:scriptvar = 2
function scopetest
{
    "scopetest before $scriptvar"
    $Global:scriptvar=$Global:scriptvar+1
    "scoptetest after $scriptvar"
}
"Before $scriptvar"
scopetest
"After $scriptvar"
Note that to be really explicit you can also use $Global:scriptvar in your output strings:
"Before $Global:scriptvar"

In PowerShell type "help about_scope" for more info
 
Frink -
>Your second method isn't suitable for my purposes as I will have lots of script-level variables.<

Be careful when using global scope variables. Your code may - unitentionally - fail epically.

However, you do have a bit of a safety net. As crobin1 stated, "you have to include the scope qualifier".

-Geates
 
Cheers. Is it just me, or is this pants?

- Frink
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top