user1863886
user1863886

Reputation:

Basic function logic

I am defining a function to switch from Player "X" to player "O". When I run this little block of code without the function, it gives me back an X. When I run this with a function defined it returns as O. What makes the difference between running it normally and running it from a Function ?

$playgame = "True"
$player = "O"

#Function
Switch-play
Write-host $player



#Switch Player turn
Function Switch-Play{
    if ($playgame = "True") {
        if ($player -eq "X") {$player = "O"}
        else {$player = "X"}
        }
}

Thanks

EDIT: At first I was in doubt about defining the variables as $script:player, but that didn't really solve anything.

EDIT: changing to Switch-Play rather than Switch-play

PS C:\Users\scout> $playgame = "True"
$player = "O"
$player
Switch-Play
$player
Switch-Play 
$player




#Switch Player turn
Function Switch-Play{
    if ($playgame = "True") {
        if ($player -eq "X") {$player = "O"}
        else {$player = "X"}
        }
}
O
O
O

Upvotes: 0

Views: 110

Answers (2)

David Martin
David Martin

Reputation: 12248

Alternatively you could return the value of player from the function:

Function Switch-Play
{
    param
    ( 
      $playgame,
      $player
    )
    if ($playgame -eq $true) 
    { 
        if ($player -eq "X") 
        {
            $player = "O"
        }
        else 
        {
            $player = "X"
        }
        $player
    }
}

$player = "O"
$player = Switch-play -playgame $true -player $player
Write-host $player

Upvotes: 0

CB.
CB.

Reputation: 60918

Variable Scope issue here. Change function like this:

Function Switch-Play{
    if ($playgame) {
        if ($global:player -eq "X") 
            {
              $global:player = "O"}
        else 
            {                
              $global:player = "X"
            }
        }
}

Reading about scope: http://technet.microsoft.com/en-us/library/hh847849.aspx

Upvotes: 2

Related Questions