One additional feature of custom commands is the ability to pass an inconstant number of arguments that changes each time you use the command.
For example, you might want to add two numbers together the first time, but then later add five numbers. You could create separate commands for each of these, perhaps named Add2 and Add5, but it would be simpler if there was a single command that could add any number of values:
Define Command AddAll($list ...)
$sum = 0
ForEach $number in $list
$sum += $number
End
Return $sum
End
$ten = AddAll(4,6)
$nine = AddAll(3,3,3)
$fourteen = AddAll($ten,1,1,1,1)
The ellipsis character (three periods) defines the last argument in a command as an Array filled with any number of values.
This special kind of list argument must always be the last argument, but can be preceded by normal arguments as well, eg:
Define Command AddAllAndMultiply($multiplier, $list ...)
$sum = 0
ForEach $number in $list
$sum += $number
End
Return $sum * $multiplier
End
$ten = AddAllAndMultiply(2, 4, 1)
Previous Chapter Variable Scope |
<< index >> |
Next Chapter Reusing Commands |