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 actually 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 was passed and it 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 passing it 1 or 2 parameters.

If a parameter is not passed, the variable used for that parameter cannot be used in procedure or function – although it is named, it does not exist. For example, the following 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 10 (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 10 (nAmount/100 * iApplyPercent) to nDiscount

   Send ShowDiscount nDiscount

End_Procedure

Note that this technique is also supported for global procedures and functions.