I've got simple script, which creates 2d char array, and invokes function, which should to fill that array with given char.
[int]$size = Read-Host "Please, enter the board size"
$playerBoard = New-Object 'char[,]' $size,$size
Fill-Boad-With-Symbol($playerBoard,'*',$size)
and here is the function
function Fill-Boad-With-Symbol([char[,]]$board, [char]$symbol,[int]$boardSize){
for ($i=0; $i -lt $boardSize; $i ) {
for ($j=0; $j -lt $boardSize; $j ) {
$board[$i,$j] = $symbol
}
}
}
But when executing this code i get the following error:
Cannot process argument transformation on parameter 'board'. Cannot convert the "System.Char[,]" value of type "System.Char[,]" to type "System.Char"
...
Fill-Boad-With-Symbol($playerBoard,'*',$size)
I kindly ask to explain, what am I doing wrong?
CodePudding user response:
As in my comment, in PowerShell, arguments are either positional or named, your first error is the way you're passing arguments to your function. By doing this:
Fill-Board-Symbol($playerBoard,'*',$size)
PowerShell will interpret it as if you were passing an object[]
(object array
) which 1st element array[0]
will be the $playerBoard
, 2nd element would be a *
and 3rd element, an int
to the first parameter of your function -Board
which is type constraint to char[,]
.
PowerShell will then attempt type conversion from object[]
to char[,]
and it will fail with that exception you see.
Example:
Given these variables:
$playerBoard = New-Object 'char[,]' 2,2
$symbol = '*'
$size = 2
Grouping them together (...)
we can inspect it's type:
PS /> ($playerBoard, $symbol, $size).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
If we attempt to convert it to [char[,]]
:
PS /> [char[,]]($playerBoard, $symbol, $size)
InvalidArgument: Cannot convert the "System.Char[,]" value of type "System.Char[,]" to type "System.Char".
Try doing this instead:
[int]$size = Read-Host "Please, enter the board size"
$playerBoard = New-Object 'char[,]' $size,$size
function Fill-Board-With-Symbol {
param(
[char[,]]$board,
[char]$symbol,
[int]$boardSize
)
for ($i=0; $i -lt $boardSize; $i ) {
for ($j=0; $j -lt $boardSize; $j ) {
$board[$i,$j] = $symbol
}
}
$board # => This is your output
}
$newBoard = Fill-Board-With-Symbol -Board $playerBoard -Symbol '*' -BoardSize $size
$newBoard