Links
Comment on page

Functions

Anonymous Function Declaration

Declaring functions in Loop is easy, you just use the fn keyword accompanied by it's arguments and function body. For example:
fn(int one, int two, int three) {
// Body
}
If you'd like to call a function again (which is it's primary use-case of course). Then you can assign a function to a variable, which is as easy it sounds.
// Notice the "fn :="
added := fn(int one, int two, int three) {
return one + two + three
}
// Now you can call the function like this:
adder(1, 2, 3) // Returns 6

Named Functions

Named functions differ from anonymous functions in that it is possible to recursively call them. Creating a named function is easy and just requires providing a name to the fn keyword.
fn double(int x) {
x + y
}

Closures

"A closure is a record storing a function together with an environment" - Wikipedia
Because functions are considered first-class in Loop it means they can also contain their own environment. Creating a function automatically creates an environment for that function. Take this as an example:
closure := fn(int x) {
num := x
return fun(int y) {
return x * y
}
}
outer := closure(100) // Returns a function reference
outer(10) // Returns 1000

Last modified 1yr ago