-
Notifications
You must be signed in to change notification settings - Fork 3
Functions
Functions are a stored piece of code that can be run multiple times each time with different parameters to process and to return a value based upon.
There are 3 ways of defining a function in MeowScript:
The long notation looks like this:
func name([parameters]) -> return_type {
...
}
Valid return types are:
- Number
- String
- List
- Any
- Void
- Object as well as the name of any current defined struct.
This is the same as the long notation, but you are allowed to remove the -> return_type and MeowScript assumes you mean Any.
The short notation looks like something like this:
func name([parameters]) => <ongoing...>
This function type instantly returns whatever comes after the => and is not limited to any amount of following arguments.
Examples:
func num() => 12
func calc() => 1 + 2 * 3
func foo() => {calc();num()}
func bar() => [9,"hi",6]
You can return two ways:
To explicitly return a value, you use the return command.
return 12 # returns 12
return # returns void
After a return no more lines are executed.
If no explicit return was found and the last executed line returned something, we use this command.
An example of implicit returns:
func foo() => 12
func bar() {
...
foo() # we return 12
}
func baz() {
new z "hehe"
z # we return "hehe"
}
A parameter list looks usually something like this:
([name [:: Typename],...])
Typenames are the same as a return_type. If no type is provided, Any is assumed.
Calling a function is very simple:
function_name(<params>)[!]
If the arguments don't match any overload of the function an error is thrown.
The optional ! after a function calls tells MeowScript to throw away whatever the function returns, even if it's void.
Two functions can share the same name as long as their parameters differ from each other.
Here an example where we overload foo three times.
func foo() => 12
func foo(a :: String) -> Number {
return {number(a)}
}
func foo(a :: List) {
print "This is a list!!"
}
foo() # 12
foo("123") # 123
foo([1,2,3]) # This is a list!!
foo()! # nothing