Passing Variable Number of Parameters
When calling a procedure or function method, you are allowed to pass a variable number of parameters. If a procedure or function might receive a variable number of parameters, you need to check how many parameters were actually passed and only use the parameters that were passed.
Num_Arguments
You can check for the number of parameters passed by using the Num_Arguments variable.
In the following example, the procedure ApplyDiscount checks to see if one or two parameters were passed and adjusts its logic accordingly:
Class cMyButton is a Button
Procedure ApplyDiscount number nAmount integer iPercent
Number nDiscount
If (Num_Arguments = 2) Begin
Move (nAmount / 100 * iPercent) to nDiscount
End
Else Begin
// If percent not passed, apply standard discount of 10%
Move (nAmount * .10) to nDiscount
End
Send ShowDiscount nDiscount
End_Procedure
Procedure OnClick
Send ApplyDiscount nAmount 50 // Apply 50% discount
Send ApplyDiscount nAmount // Apply standard discount
End_Procedure
End_Class
In the above example, ApplyDiscount could be successfully called by passing it either 1 or 2 parameters.
If a parameter is not passed, the variable used for that parameter cannot be used in the procedure or function – although it is named, it does not exist. For example, the following code would generate a runtime error when passed a single parameter:
Procedure ApplyDiscount number nAmount integer iPercent
Number nDiscount
If (Num_Arguments = 1) Begin
Move 10 to iPercent // This will not work!
End
Move (nAmount / 100 * iPercent) to nDiscount
Send ShowDiscount nDiscount
End_Procedure
In the above example, you may not move a value to iPercent because the variable is not defined if the parameter is not passed. The proper code for this sample would be:
Procedure ApplyDiscount number nAmount integer iPercent
Number nDiscount
Integer iApplyPercent
If (Num_Arguments = 1) Begin
Move 10 to iApplyPercent
End
Else Begin
Move iPercent to iApplyPercent
End
Move (nAmount / 100 * iApplyPercent) to nDiscount
Send ShowDiscount nDiscount
End_Procedure
Note that this technique is also supported for global procedures and functions.