Functions in VG Language
Functions allow you to group code that performs a specific task. They can take parameters and return values.
Defining Functions
To define a function, use the function
keyword followed by the function name and parameters:
Calling Functions
To call a function, use its name followed by parentheses containing any arguments:
Return Statement
The return
statement specifies the value to be returned from a function:
Functions without a return
statement or with an empty return
statement return null
.
Parameters
Functions can have multiple parameters, separated by commas:
function greet(firstName, lastName, age) {
return "Hello, " + firstName + " " + lastName + "! You are " + age + " years old.";
}
var greeting = greet("John", "Doe", 30);
Function Documentation
You can document your functions using special comment blocks:
/## Calculates the sum of two numbers
# @param a The first number
# @param b The second number
# @return The sum of a and b
# @author John Doe
##/
function add(a, b) {
return a + b;
}
Functions in Libraries
Functions can be organized into libraries and namespaces:
library MathUtils {
namespace basic {
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
}
}
To use these functions, import them:
Recursive Functions
Functions can call themselves (recursion):
function factorial(n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
var result = factorial(5); ## result = 120
Scope
Variables declared inside a function are only accessible within that function:
function test() {
var localVar = 10;
print(localVar); ## Works fine
}
test();
print(localVar); ## Error: localVar is not defined
However, functions can access variables from their containing scope:
var globalVar = 20;
function test() {
print(globalVar); ## Works fine, accesses the global variable
}
test();
Best Practices
-
Use Descriptive Names: Choose function names that clearly describe what the function does.
-
Keep Functions Small: Each function should do one thing and do it well.
-
Document Your Functions: Use documentation comments to explain what the function does, its parameters, and return values.
-
Avoid Side Effects: Functions should ideally not modify variables outside their scope.
-
Return Early: Return as soon as you have the result to make your code more readable.