L1VM - course 04

functions

Here I show a simple math function calculating the square of a number. We will use double floating point numbers.

A double number is defined by a “set” call like this:

``````(set double 1 a 2.0)
``````

The “1” stands for one number. We can define an array by setting a higher number as “1”.
But arrays are a topic for a later course part.

Here is our “square” function:

``````(square func)
(set double 1 num 0.0)
(set double 1 square 0.0)
(num stpopd)
{square = num num *}
(square stpushd)
(funcend)
``````

It defines two variables: “num” and “square”. With “stpopd” we get the number from the stack. The stack is needed to push and pull variables to and from it. With: “ {square = num num *}” we calculate the square of the number. As the last step the “square” variable is pushed on to the stack. So we can get the result back in the main function.

The call looks like this:

`````` // call square function with numbers a, b and c:
(a :square !)
(as stpopd)
print_d (as)
print_n
``````

The “print_d” and “print_n” are macros defined in the include file: “intr.l1h”. With “print_d” a double number is printed out. The “print_n” just puts a new line out. So you can use them for a formatted text output.

In the variable “as” we get the square of the number “a” back.

Here is the full program:

``````// square-func.l1com
//
// calculate square of number
//
#include <intr.l1h>
(main func)
(set int64 1 zero 0)
(set double 1 a 2.0)
(set double 1 b 13.5)
(set double 1 c 7.8)
(set double 1 as 0.0)
(set double 1 bs 0.0)
(set double 1 cs 0.0)

// call square function with numbers a, b and c:
(a :square !)
(as stpopd)
print_d (as)
print_n

(b :square !)
(bs stpopd)
print_d (bs)
print_n

(c :square !)
(cs stpopd)
print_d (cs)
print_n

exit (zero)
(funcend)

(square func)
(set double 1 num 0.0)
(set double 1 square 0.0)
(num stpopd)
{square = num num *}
(square stpushd)
(funcend)
``````

Here is the program output:

``````\$ l1vm prog/square-func -q
4.0000000000
182.2500000000
60.8400000000
``````