fun

In your X3 programming language, the "fun" keyword is used to define a function. Functions are blocks of reusable code that perform a specific task. Here's how you would use the "fun" keyword in your X3 language to define and use functions:

Function Definition:

# Using 'fun' to define a function
fun greet(name)
    show("Hello, {name}!")
end

Explanation:

  • In this example, a function named "greet" is defined using the "fun" keyword.

  • The function takes one parameter named "name".

  • Inside the function block, the code prints a greeting message using the provided name.

Function Call:

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

Explanation:

  • After defining the "greet" function, you can call it by using its name followed by parentheses containing the arguments.

  • In this case, the function is called with the argument "John", so it will print "Hello, John!".

Returning Values:

# Defining a function that returns a value
fun square(x)
    return x * x
end

# Calling the 'square' function and storing the result
var result = square(5)
show("Square of 5 is: {result}")

Explanation:

  • This example defines a function named "square" that takes one parameter, "x", and returns the square of that value.

  • The result of calling the function with an argument of 5 is stored in the variable "result", and then it's printed.

Nested Functions:

# Defining a function with nested functions
fun outerFunction()
    fun innerFunction()
        show("Inside inner function.")
    end

    print("Inside outer function.")
    innerFunction()
end

# Calling the 'outerFunction' which will also call 'innerFunction'
outerFunction()

Explanation:

  • Functions can be defined inside other functions, creating nested functions.

  • In this example, the "outerFunction" contains a nested function named "innerFunction".

  • When the "outerFunction" is called, it prints a message and then calls the "innerFunction", which prints another message.

By incorporating the "fun" keyword in your X3 language, you provide users with the ability to modularize their code and improve reusability by defining functions to encapsulate specific tasks or computations.

Last updated