return instruction

The return instruction is used to return from a function. Execution in the function is stopped and execution continues in the script that called the function.

The syntax depends on the function’s number of output arguments:

  • no output arguments

    If a function has no output arguments then a return instruction can be used anywhere in the function’s script to stop execution and return control to the caller of the function.

    If no return instruction is used in the function then the function implicitly returns after executing the last instruction in the script.

    Example:

    function greet ( name string or null )
    
        if name is null then
            write_line ( "Hello" )
            return // explicit return
        .
        write_line ( """Hello {{name}}""")
        // implicit return
    .

    Usage:

    greet ( "Bob" )
    greet ( null )

    Output:

    Hello Bob
    Hello
  • one output argument

    If a function has one output argument, then the return keyword must be followed by an expression that represents the value returned to the caller.

    Example:

    function count_digits ( string ) -> zero_pos_64
    
        return string.stream.filter ( { char => char.is_digit } ).count
    .

    Usage:

    const c1 = count_digits ( "a1b2c3" )
    assert c1 =v 3L
    
    const c2 = count_digits ( "abc" )
    assert c2 =v 0L
  • more than one output argument

    If a function has more than one output arguments, then the return keyword must be followed by an assignment for each output argument, separated by a comma.

    Example:

    The following function get_first_and_last takes a string as input and returns two values:

    first: the first character of input string

    last: the last character of input string

    function get_first_and_last ( string ) -> ( first character, last character )
    
        return first = string.get ( 1 ),
            last  = string.get ( string.size )
    .

    Usage:

    get_first_and_last ( "abc" ) (
        const first = first
        const last = last )
    assert first =v 'a'
    assert last  =v 'c'

results matching ""

    No results matching ""