return

In your X3 programming language, the "return" keyword is used within a function to specify the value that should be returned to the caller. When a function encounters a "return" statement, it immediately exits, and the specified value (if any) is passed back to the point in the code where the function was called. Here's how you would typically use the "return" keyword in your X3 language:

Basic Usage:

# Defining a function that returns a value
fun add(a, b)
    return a + b
end

# Calling the 'add' function and storing the result
var result = add(3, 5)
show("The result is: {result}")

Explanation:

  • In this example, the "add" function takes two parameters, a and b, and returns their sum using the "return" keyword.

  • When the function is called with arguments 3 and 5, the result of adding them (8) is returned and stored in the variable result.

Conditional Return:

# Defining a function with conditional return
fun absoluteValue(num)
    if num < 0 then
        return -num
    else
        return num
    end
end

# Calling the 'absoluteValue' function
var absValue = absoluteValue(-5)
show("The absolute value is: {absValue}")

Explanation:

  • Here, the "absoluteValue" function calculates the absolute value of a number.

  • If the number is negative (num < 0), the function returns the negation of the number. Otherwise, it returns the number itself.

Returning Multiple Values:

# Defining a function that returns multiple values
fun divideAndRemainder(dividend, divisor)
    var quotient = dividend / divisor
    var remainder = dividend % divisor
    return quotient, remainder
end

# Calling the 'divideAndRemainder' function
var result = divideAndRemainder(10, 3)
print("Quotient: {result[0]}, Remainder: {result[1]}")

Explanation:

  • In this example, the "divideAndRemainder" function calculates both the quotient and remainder when dividing two numbers.

  • It returns multiple values using a tuple, which can be accessed and used separately after the function call.

Void Return:

# Defining a function with no return value (void)
fun greet(name)
    show("Hello, {name}!")
    # No 'return' statement needed
end

# Calling the 'greet' function
greet("John")

Explanation:

  • In some cases, a function may not need to return any value.

  • In such cases, you can omit the "return" statement, and the function will implicitly return nothing (void).

By incorporating the "return" keyword in your X3 language, you enable users to create more versatile and dynamic functions that can produce results and interact with the rest of the program effectively.

Last updated