CHAPTER 6

Function

In loose scripting, a user may define functions which have global scope. Since functions can only appear in such context, all functions in Julian are global functions.

Functions are different from class methods mainly in two aspects. First, functions are defined in the loose script, and can be placed anywhere as long as it's at the top lexical scope. Second, functions have access to global variables. Otherwise functions are quite same as static methods.

To define a function in the script, use the C-like function definition grammar.

  void fun(){
    // Minimal function that does nothing.
  }
  
  int add(int a, int b){
    return a + b;
  }

The function definition consists of return type, a function signature with parameter names, and a function body. The function parameter list can contain 0 or more parameters. The body is expected to return a value of declared return type. However, if it didn't, it will only result in a runtime error since no static validation is performed before the function is run.

  int divide(int a, int b){
    if (b = 0) {
      return a / b;
    }
    // Bug: forgot to return a value here. This will cause a runtime exception.
  }

The function has access to external, or global, variables.

  int i = 0;
  int addMore(int acc){
    i += acc;
  }
  addMore(5);
  Console.println(i); // 5

This is a basic introduction to function and is sufficient to help the user to get a lot of works done. However, there are way more important features about function in Julian. To learn more, check Functional programming.