The content on this page is written in Chinese, and then traslated into English by machine. More accurate traslations are welcome at: https://github.com/wa-lang/man/tree/master/en

Ending's law: "Any application that can be compiled to WebAssembly, will be compiled to WebAssembly eventually."

4.1. Function call

We have come across many functions in previous chapters, such as the commonly used built-in printing function println. The general syntax for function calls is:

FunctionName (actual parameter list)

Actual parameters refer to the parameters actually passed in when the function is called, corresponding to the formal parameters defined when the function is declared. The formal parameters are only valid within the function body. When calling a function in Wa-lang, parameters are passed by value. Changes to the formal parameter values within the function body will not affect the actual parameter values, for example:

// 版权 @2023 凹语言 作者。保留所有权利。

func Double(i: i32) => i32 {
    i = i * 2
    return i
}

func main {
    j: i32 = 42
    println(Double(j)) // 84
    println(j)         // 42
}

The keyword return is used to exit the function and return values. The general syntax is:

return ValueList

If a function has multiple return values, they should be separated by ,, for example:

func MulRet() => (i32, i32) {
    return 42, 13
}

Similar to formal parameters, named return values can be defined when a function is declared, for example:

func showAnswer() => (answer: i32) {
    answer = 42
    return
}

This is equivalent to:

func showAnswer() => i32 {
    answer: i32
    answer = 42
    return answer
}

Like other variables, named return values are initialized with a value of 0. If a function witch has many branches needs to return an error code, and most branch error codes have a value of 0, using a named return value can simplify the code.

Even if a named return value is declared, return can still return other values, such as:

// 版权 @2019 凹语言 作者。保留所有权利。

func showAnswer() => (answer: i32) {
    answer = 13
    return 42
}

func main {
    println(showAnswer()) // 42
}

So we can understand it this way: the named return value actually defines a set of local variables in the function body. When the return statement within the function does not specify a return value, this set of local variables is automatically filled in as the return value.