-
Notifications
You must be signed in to change notification settings - Fork 0
Functions
A function in orth is just like a function in any other language. It is a segment of code that runs from top to bottom, eventually returning to it's calling function (or looping forever, but a return is required.) Functions in orth look like this:
function(int a) foo -> int does
int b = a*3
a+=1
return b+a
The code contained within a function is all of the statements from the function declaration line to the final return statement not contained within any control-flow blocks (not within an if/else/while etc.) This means that it is illegal to write functions like so:
function(int a) foo -> int does
int b = a*3
return b
a+=1
return b+a
This is because orth no longer understands that the a+=1
and return b+a
statements are part of the function. Returns are legal within control flow blocks, e.g.
function(int a) bar -> int does
if a==0 do
return 0
done
return a+3
The syntax for declaring a function is (where bold text is a placeholder): function(arg, arg, ...) name -> return_type does
The argument list takes the form: type_name arg_name followed by a comma if there are additional arguments. For example: function(int a, float b, bool c, ptr d, SomeType long_name)
. void
is used as the return type to indicate no return.
If, in the declaration of a function, the word function
is replaced with extern
(and the does
term is omitted, as there is no body), the declaration corresponds to a function prototype in C. I.e. this instructs the compiler that function is to be resolved at compile time, and informs it to the parameters and return value of the function (and of course it's symbolic name.) An example of this is
extern(int code) exit -> void
this is equivalent to void exit(int code);
in C. One other thing to keep in mind is that extern functions may be declared with an argument list of ...
instead of the entire construct within the parenthesis. This represents the varargs implementation as in the C ABI, and currently only good for interfacing with C code. There is no support for required arguments as in C, the ellipsis must be the sole item within the parenthesis. Additionally, this removes all type checking from the call (both in the orth compiler and LLVM) - so watch out! An example of this is (linking against the libc function printf
):
extern(...) printf -> int