Functions
Creating Functions
To create functions, the function keyword can be used. This may be familiar to some from other languages that have similar keywords.
Visibility
Every function requires a predetermined visibility attribute.
| Keyword | Explanation |
|---|---|
| pub | A public function is publicly available in the module. |
| publib | A public library function is available outside of the project when imported as a library. |
| private | A private function is only available in the module it is defined in. |
Every source file serves as a different module.
Function statement:
<visibility> function <name>(<arguments>): <return type> {
<body>
}
Function definition example:
pub function name(arg1: int, arg2: float) {
// Function body
}
pub function name_2(arg1: int, arg2: float): int {
// Function body
return 0;
}
Importing Functions
We can import functions from other source files or from libc.
- To import functions from pre-compiler libraries, we can use the
externalkeyword. - When importing functions from dependencies or from other fog source files we can import the item via defining the the module path.
- We can import source files by manually defining their paths on the host system.
Here is how to import both types of functions:
// -- other.f --
pub function return_2(): int {
return 2;
}
// main.f
import "other.f";
// Import with a fully defined path
import "foo/bar/faz/test.f";
// Importing from a precompiled library (libc in this case)
external printf(msg: string, ...): void;
// Importing from a source file
import other::return_2;
// Importing from a dependency
import foo::bar::baz::hello;
pub function main(): int {
int num = return_2();
// Greet the user
hello();
printf("Returned number: %i", num);
return 0;
}
Note that we can also use variable arguments when constructing symbols for other functions. VarArgs cannot be used in a Fog function.