Sometimes it may be desirable to use a custom command without knowing its name ahead of time. For example, you might want to apply some command to every value in an array, but without choosing a particular command ahead of time. You can do so using the Call command:
Call commandName, [arg1], [arg2] ... [argN] v2.1
The first argument is the name of the command to call. All subsequent arguments are passed to that command.
NOTE: instead of a command name, you may instead pass a reference created using the @Command construct.
In its simplest form, the Call command merely activates a custom command:
Define Command SayHello($name)
Prompt "Hello $name!"
End
Call "SayHello", "Ambrose" # prompts the user with "Hello Ambrose!"
However, consider the original scenario, where we want to modify all values in an array:
Define Command Double($value)
Return $value * 2
End
Define Command AddOne($value)
Return $value + 1
End
Define Command ApplyCommandToArrayValues($array, $command)
ForEach $index, $value in $array
$newValue = Call $command, $value
$array[$index] = $newValue
End
End
$numbers = Array.new(1, 2, 3)
ApplyCommandToArrayValues($numbers, "Double")
# the array $numbers is now (2,4,6)
ApplyCommandToArrayValues($numbers, "AddOne")
# the array $numbers is now (3,5,7)
The above macro uses the dynamic nature of the Call command to increase its flexibility.
Instead of identifying a command using a string, which can be error prone due to typos, you may instead capture a reference to a command using the @Command construct (added in v2.1). Extending the prior example:
$apply = @command(AddOne)
ApplyCommandToArrayValues($numbers, $apply)
Or more compactly:
ApplyCommandToArrayValues($numbers, @command(AddOne))
This has the benefit of catching any spelling errors in the command name when parsing the macro, instead of possibly reporting an error when running that line of the macro.
Previous Chapter Reusing Commands |
<< index >> |
Next Chapter Find and Replace |