Functions - markpwns1/Dormez GitHub Wiki
Functions in Dormez are mostly the same as in other languages as well. Here's an example:
declare function exampleFunction {
console.print("Hello world");
}
Then you can call the function like in other languages.
exampleFunction();
This will print 'Hello world'. Functions can also take parameters:
declare function addAndPrint : x, y {
console.print(x + y);
}
And finally, functions can also return values:
declare function add : x, y {
return x + y;
}
You can also use return for flow control reasons:
declare function func : x {
if x > 0 {
return;
}
// ...
}
When a value is not returned, a function will return void, which is technically a primitive type, like C#'s null.
Function Scoping Rules
Function scoping in Dormez is quite different than in most languages. The important part is that a function is not outside the scope that called it. Refer to the following example:
declare function foo {
return x + y;
}
declare function bar {
declare x = 5;
declare y = 10;
console.print(foo());
}
bar();
This will print 15. This is because x and y are still in scope. But why are they still in scope? That's because in Dormez, all functions are basically treated as though they were just code appended where they are called. The code above can pretty much be considered to be the code below:
declare function bar {
declare x = 5;
declare y = 10;
console.print(function { return x + y; }());
}
bar();
Of course, that's not actually how the Dormez interpreter handles functions internally, so rest assured that calling a function is efficient and comes with minimal overhead.