In Artsy, functions are called actions. They are self-contained modules of code that perform specific tasks and can be used multiple times.
A value-returning action returns a value when called.
For example, consider the following action that returns the sum of two numbers:
# Function has 3 components
action int add(int number){
# 1. "action" to state it is a function
# 2. "int" type of function (int, string, float, etc.)
# 3. "add" name of the function
}
# Add two numbers and return the result
action float addNumbers(float a, float b) {
declare result as float;
let result = a + b;
report result;
}
To use this action, you can assign the returned value to a variable:
let result = addNumbers(3.14, 2.718);
Or you can directly print the result:
print addNumbers(1.0, 2.0);
A void action does not return a value. It simply performs a task or prints a message.
For example, consider the following action that prints a message to the console:
# Print a message to the console
action printMessage() { # don't put the type of function
print "Hello, world!"; # means to return nothing (void)
}
To use this action, you simply call it:
printMessage();
Here's an example that combines both types of actions to create a simple calculator:
# Add two numbers and print the result
# Multiply two numbers and return the result
action float multiply(float left, float right) {
declare result as float;
let result = left * right;
report result;
}
# Divide two numbers and return the result
action float divide(float left, float right) {
declare result as float;
let result = left / right;
report result;
}
# Usage example
declare a as float;
declare b as float;
let a = 10.0;
let b = 5.0;
declare c as float;
let c = multiply(a, b); # c is now 50.0
print c;
addline;
declare d as float;
let d = divide(a, b); # d is now 2.0
print d;