7. Functions

Functions in S2 can be simple functions, methods of a class, or call functions written in the backend language from the builtin layer.

Functions can return data in any simple internal datatype, or void if no return data is required.

7.1. Declaration

Declaring a function within a class is done as follows:

class SomeClass { function do_stuff(int para1, string para2) : string;

This declares a function called do_stuff in the SomeClass class with two parameters and which returns a string. The colon and type keyword may be omitted where a function will return void (no value).

Functions outside classes are declared in the same way:

function do_global_stuff(int para1, string para2);

Functions outside classes do not need to be declared, but if they are not declared they must be defined before they are called.

Built-in functions can be declared in the core layer using the builtin keyword in the function prototype:

function builtin ehtml(string s) : string; class string { function builtin ends_with (string sub) : bool;

Functions can have some or no parameters, in the latter case the parentheses may be omitted in declaration. If several functions of the same name exist with different parameters, they can be defined as follows:

function dostuff(int para1); function dostuff;

Non-class (global) functions can be implemented when they are declared:

function do_global_stuff() { print "I'm doing stuff!";

Class functions (methods) must first be declared within the class they will apply to, and can then be implemented outside the class declaration as follows:

function SomeClass::do_stuff() { print "I'm doing stuff!";

It is not permitted to implement a builtin function. These will instead be mapped onto some code written in the host language in the S2 backend.

Layouts are allowed to add new methods to a class without pre-declaration, but with a few special constraints. Firstly, the method must be declared and implemented before it is used. Secondly, the method name must begin with lay_, to avoid problems in the future when new methods may be added to the core layer with the same name.

7.2. Calling

Functions outside classes can be called using the following syntax:


Functions in classes are envoked from an instance of the class as follows:


Note that the parentheses are required when envoking a function.