0

我正在定义一个从播放器“X”切换到播放器“O”的函数。当我在没有函数的情况下运行这个小代码块时,它会给我一个 X。当我使用定义的函数运行它时,它返回为 O。正常运行它和从 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"}
        }
}

谢谢

编辑:起初我怀疑将变量定义为 $script:player,但这并没有真正解决任何问题。

编辑:更改为 Switch-Play 而不是 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
4

2 回答 2

2

变量范围问题在这里。改变这样的功能:

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

阅读范围:http ://technet.microsoft.com/en-us/library/hh847849.aspx

于 2013-01-17T15:08:07.773 回答
0

或者,您可以从函数返回 player 的值:

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
于 2013-01-17T16:14:35.117 回答