spool-lang / Spool-Legacy-Repo

Legacy repo for the Spool programming language.
3 stars 0 forks source link

Functions #5

Open RedstoneParadox opened 5 years ago

RedstoneParadox commented 5 years ago

Basics

Functions are declared with the func keyword, followed by the name, a list of parameters inside the parenthesis, and -> followed by return type followed by code in curly brackets. Parameters are declared in the same way as a variable or constant (See #3: Variables, Constants, Getters and Setters), except that constants can be declared without the const keyword.


func fooThing(param : Int, var otherParam: Float) -> Boolean {
    return true
}

If a function does not return anything, the return type should be None:


func noReturn() -> None {

}

Functions are called like so:


main {
    fooThing(1, 1.0f)
    noReturn()
}

Default Parameters

Like variables, parameters can have a default value declared in the same way. When calling a function with default parameters, you can just have a blank space to represent the default value or omit it entirely if the last parameter is a default:


main {
    foo(1, , 3)
}

func foo(a : Int, b : Int = 2, c : Int, d : Int = 4) -> None {

}

Note that this does not work with generic types (#9) as the actual type is not known beforehand and thus the default value may not be of the later-specified type.

Varargs

Declaring a parameter as varargs allows for multiple arguments to be passed to that parameter. Internally, the values passed to varargs are considered to be an array and its elements are accessed using the index operator. Varags are written and called like so:


func variableArguments(varags Int : x) -> None {

print(x[1]);
print(x[2]);

}

main {
    variableArguments("Hello ", "world!")
}

This code prints "Hello world!"

Limiting Varags Count

In some cases, it may be beneficial to limit the number of arguments that can be passed to a varargs parameter you can specify a range by using the to keyword before the varargs keyword or else use the min and max keywords to only specify a minimum and maximum value.


#Between 1 and 3 arguments may be passed to this function.
func rangeVarargs(1 to 3 varags Foo : foo) -> None {

}

#At least 2 arguments must be passed to this function
func minVarargs(min 2 varargs Foo : foo) -> None {

}

#No more than 5 arguments can be passed to this function
func maxVarargs(max 5 varags Foo : foo) -> None {

}