User-Defined Function Examples

Here is a simple example of a function to format a decimal integer value as a hex string:

Function Fn'Dec2Hex$(decval as f8:inputonly,flags=0 as b2:inputonly,width=0 as b2:inputonly) as s16

   map1 hexon,f

   xcall MIAMEX, MX_GETHEX, hexon      ! see if we are in hex mode

   if (not hexon) then xcall MIAMEX, MX_SETHEX, 1          !  if not, set it

   xcall MIAMEX, MX_OCVT, decval, width, OT_MEM or flags, Fn'Dec2Hex$

   if (not hexon) then xcall MIAMEX, MX_SETHEX, hexon  ! restore octal

EndFunction

 

Note that although unpassed parameters will default to zero (or "" for strings), specifying default initial values (=0) in the function definition (flags=0 and width=0) allows the caller to explicitly specify width by name without having to specify flags, e.g. ...

? Fn'Dec2Hex$(value,width=10)   ! width = 10 (by name)

? Fn'Dec2Hex$(value,10)         ! flags = 10 (by position)

 

This slightly more complex example of a function to allocate a file illustrates some additional capabilities, such as static local variables and error trapping:

Function Fn'Alloc(spec$ as s120, bytes as b4) as b2

map1 blocks,f,6

static map1 s'tot'allocations,f

 

on error goto Trap  ! local error trap

 

blocks =  int((bytes + 511) / 512)

allocate spec$,blocks

s'tot'allocations = s'tot'allocations + blocks

Fn'Alloc = 0    ! unnecessary but explicit

exitfunction    ! exit function

 

Trap:     ! note this label doesn't conflict with outer TRAP

Fn'Alloc = err(0)   ! set return value to error #

resume endfunction  ! clear Basic error and return

EndFunction 

 

In the above example, the local static variable s'tot'allocations will get incremented by the number of blocks each time the function is called. (It doesn't serve any purpose in this example, as there is no way to retrieve it, but it might, for example, be used to prevent the program from allocating too many blocks in one session, or for computing statistics.)