Functions
A function is a way to reuse a part of code. By passing parameters to a function, one can adapt a process to different cases, and this is the mission of the programmer to define how to split a processing into functions. The Scriptol language has lot of builtin functions, and it uses directly all functions of the target language's library, Php or C++. In this chapter we will study how to define new functions.
Defining a function
A function begins with an interface that says how is has to be called, followed
by a block of statements, and terminated by the "return" keyword.
type [type]* name ( argument [, argument]* ) [:]
... instructions ...
return [type [, type]*]
That means:
- a type or several type to return,
- the identifier,
- a list of argument between parenthesis,
- optionally a colon, required if a statement is on the same line,
- the body, one or several instructions,
- the return keyword, followed by zero, one or several values to return, according
to the heading.
Inside the body of the function, any statements can be inserted not another
function or high-level declaration (class, enum...)
Simple function | int
multiply(int x, int
y) int z z = x * y return z |
This can be written simply: | int multiply(int x, int y) return x * y |
Function returning nothing
If the function returns nothing, the return type is void, and the return
statement has no parameter.
void
disp(text t) print "a text:", t return |
Multiple return
If the function return several values, it must have also several return
types and the return statement has several parameters (in the same order that
the return types).
Function returning two values | int,
int coordinate(int
num) int x = mytable[num].x int y = mytable[num].y return x, t |
More on return
Sometime the return seems to be useless..
Example of function | int
addabs(int x, int
y) if y < 0 return x - y else return x + y /if return 0 |
The ending return is unreachable, but is is required anyway and it must have the right format, according to the heading.
But it is always possible to write simply a such function, see below:
Function rewritten: | int
adabs(int x, int
y) if y < 0 return x - y return x + y |
Scope and function
A scope is a level inside a space of visibility.
A function opens a new scope for all variables declared inside. If the function
is at the global level, all global variables compiled before the function
are visible in the function. Inside a function, a variable can't be declared
with same name that a global variable. This rule applies also inside methods
of classes.
If the function is a method of a class, all variables declared in the class
before the function are visible in the function.
Objects declared in the function are visible in embedded control structures.
Identifiers still in use can't be reused inside embedded blocks too.
Exercises |
1) Here is a small script to calculate the n power of a real number. print z |