Return to homepage

DOSATO

Copyright © 2024 Sebastiaan Heins

1.5 Functions

Functions

Functions are blocks of code that can be called from anywhere in your program.
Functions can be created with the define keyword.
Functions can be called with the do keyword.
Simple function example:

define void sayHello() {
    do say ("Hello world")
}

This function can be called with the do keyword:

do sayHello() // Hello world

Let's break down the function declaration:

define // Define is used as a function declaration keyword
void // Void is the return type of the function (more on this later) (optional)
sayHello // The name of the function
() // The parameters of the function
{ // The start of the function block
    do say ("Hello world") // The code inside the function
} // The end of the function block

Parameters

Functions can have parameters.
Parameters are used to pass data into a function.
Parameters are declared inside the parenthesis after the function name.
Parameters are seperated by commas.
Parameters must have a set type.
Parameters can be used inside the function.
Example of a function with parameters:

define void sayHello(string name) {
    do say ("Hello " + name)
}

The function takes 1 parameter, the name of the person to say hello to.
The parameter is used inside the function.
You can use the function like this:

do sayHello("Robotnik") // Hello Robotnik

Return types

Functions can have optional return types.
Return types are used to determine what type of data the function returns.
Return types are declared after the define keyword.
Any variable type can be used as a return type.
If a function does not return anything, the return type void can be used.
Example of a function with a return type:

define int addNumbers(int a, int b) {
    return a + b
}

return is used to return a value from a function.
return has the value to return.
return also stops the execution of the function.

Info!
return can also be used to end a void function.
return can be used anywhere in a function.

The function returns the value of a + b.
You can use the function like this:

make int sum = addNumbers(5, 10) // sum is 15

The parameters will be copied into the function.
So the original variables will not be changed.
Example:

define addOne(int a) {
    set a += 1
    do say (a) // a is 6, number is still 5
}

make int number = 5
do addOne(number) // number is still 5, number did not change
do say (number)

Info!
We will learn more about scopes in a later chapter 1.7 Scopes.