我正在定义一个从播放器“X”切换到播放器“O”的功能。当我在没有函数的情况下运行这个代码的小块时,它给了我一个X.当我用定义的函数运行它时,它返回为O.在正常运行和运行它之间有什么区别来自一个函数?
$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
答案 0 :(得分: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
答案 1 :(得分:0)
或者你可以从函数中返回玩家的值:
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