HTBasic Help
×
Menu
Index

SUB, DEF FN, and  CSUB

 
A CSUB context is a compiled subprogram created with special tools outside of HTBasic. It is loaded into memory with the LOADSUB statement and removed from memory with the DELSUB statement. It is invoked with a CALL statement.
 
A subprogram is typically referenced by explicitly naming it. For example, to call a subprogram named GetDat, use the statement:
 
CALL GetDat
 
In several statements, it is also possible to name the subprogram using a string expression. This allows the name of the subprogram to change dynamically as the program runs. The subprogram must be specified with the initial character in uppercase, and subsequent characters in lowercase. For example:
 
CALL A$
 
If A$="GetDat", the statement will call the subprogram named GetDat. If A$ has some other value, the statement will call some other subprogram. The string expression specifying the subprogram name is called a "subprogram pointer" because it "points" to the subprogram rather than explicitly naming it. As the expression changes, the pointer points to different subprograms. Subprogram pointers are allowed in CALL, INMEM, LOADSUB, DELSUB, and XREF statements.
This example shows one use for subprogram pointers:
 
10  IF Case=1 THEN
20    Method$="Real"
30  ELSE
40    Method$="Complex"
50  END IF
60  IF NOT INMEM(Method$) THEN LOADSUB Method$
70  CALL Method$ WITH(X,Y,Z)
80  DELSUB Method$
90  END
 
A User Defined Function context begins with a DEF FN statement, optionally defines parameters, ends with a FNEND statement, can be invoked from within an expression by referencing its name, and can be passed arguments, either by reference or by value. When it terminates, it returns a value with a RETURN statement. The expression then continues to evaluate, using the returned value in place of the function reference.
 
The defined function can return either a numeric value or a string value. If it returns a string value, the function name must end with a dollar sign ($) and the RETURN statement must specify a string value. For example:
 
100  PRINT "Today is: ";FNToday$
110  END
. . .
120  DEF FNToday$
130    A$=DATE$(TIMEDATE)
140    RETURN A$[1,6]
150  FNEND