MC-Basic:SUB ... END SUB

From SoftMC-Wiki
Jump to: navigation, search
Language: English  • 中文(简体)‎

The Sub and End Sub keywords are used to delimit a subprogram within a task. The subprogram(s) must appear after the main section of the code (delimited by PROGRAM..END PROGRAM). Local variables, defined using only DIM, appear after the Sub keyword, but before the code. Subprograms are executed using the CALL keyword.

<name> is the subroutine name.
<type_1> to <type_n> are the types of the parameters.
<p_1> to<p_n> are the names of the parameters passed to the subroutine. Parameters are variables used inside the subroutine code; when the subroutine is called, the values of the variables are replaced by the calling values. By default, parameters are passed by reference. {ByVal} is an option to specify that the parameter is passed by value.

{local variables declaration} declares variables local to the subroutine.

{subroutine code} defines the algorithm to compute the returned value. Subroutines may be recursive.

Arrays can only be passed by reference. If you try to pass a whole array by value, the translator returns an error. The syntax for an array is:

SUB <name> ({<p_1>([*])+ as <type_1>}…{, <p_n>([*])+ as <type_n>})

{ local variable declaration }

{ subroutine code }

END SUB

where

<p_l>  : name of array variable

<p_n>: name of array variable

[*]       : dimension of array without specifying the bounds of it

+         : means one or more

Syntax

SUB <subprogram name>
          <subroutine code to execute>
END SUB

SUB <name> ({ {ByVal} <p_1> As <type_1>}…{, {ByVal} <p_n> As <type_n>})
       {local variable declaration}
       {subroutine code}
END SUB

Calling the subroutine:

<name>( <p_1>, ... ,<p_n> )

In case there are zero arguments, the parentheses will be empty.

Availability

All versions

Type

Parmeters: Long, Double, String, Joint, Location, user defined structures, Generic Axis, Generic Group, Moving Frame (by reference only), Cam (by reference only), Comp (by reference only), Semaphore (by reference only), user defined Error and Note (by reference only).

Default


Scope                   Task

Limitations

Arrays are passed only by reference.

Examples

DIM SHARED lastloop as LONG

PROGRAM
       lastloop=10
       Attach a1
       Move a1 100
       Call a1_Move(LastLoop)

END PROGRAM

SUB a1_Move(lastLoop as Long)               'Pass parameters by reference

DIM Index as LONG
       For Index = 1 to lastloop
                   Move a1 1 abs = 0
       Next Index

END SUB

Array Example:

SUB mean(x[*][*] as DOUBLE, TheMean[*] as LONG)

DIM sum as DOUBLE

DIM I as LONG

FOR i = 1 to 100

sum = sum + x[i][1]

NEXT i

TheMean[1] = sum/100

END SUB

See Also