This document specifies the language’s syntax by showing some code examples. You can see the Clever parser grammar on Clever grammar page.
Everything in a line after // is considered comment and it is discarded by the Clever interpreter.
// Comment
y = x; // Performs a copy
Multi-line comments are similar to the C one.
/* This comment can be
splitted in several lines. */
var a = 'foo'; // get_type(a) == String
a = Foo.new(arg1, arg2); // get_type(a) == Foo
var foo;
assert(foo == null);
const foo = 'bar';
foo = 'baz'; // throws an Exception
function add(x, y) {
return x + y;
}
var myfunction = function(x, y) { return x + y; };
function test(msg, func = println) {
func(msg);
}
test("hello"); // prints 'hello'
var foo = doFoo();
var sum = add(1, 3);
function abc() {
return function() {
return 3;
}
}
println(abc()()); // 3
function show(args...) {
args.each(println);
}
show(1, "foobar");
var f = function (x) {
return function () {
return x;
};
};
var a = f(123);
var b = f(321);
print(a(), "-", b()); // 123-321
Examples of construction of native data types in Clever. For full reference (methods, properties, etc) please refer to: Types
var str = 'fooo';
var myint = 1;
var otherint = 0xC1E4E8;
var adouble = 3.141517;
var biginteger = 1234567891011121314151617181920;
var bool = (true || false);
var arr = [1, 'foo', true, Foo.new(x)];
var x = arr[0];
var z = arr.at(0);
arr[2] = false;
var map = {'name': 'Clever', 2: 'foo'};
var empty = { : };
var name = map['name']; // Null if an element with key 'name' doesn't exists
map[3.1415] = 'pi';
The name rule for type creationg is: the name must start with an upper case letter.
class Foo {
var a;
function setA(v) {
this.a = v;
}
function getA() {
return this.a;
}
}
As seen below, access to properties are done by using the this variable.
To declare a constructor you need to declare a function using the same name than the type itself. See below:
class Foo {
function Foo() {
// Constructor
}
}
On condition, just the literal boolean false and null are evaluated to false value. Everything else is a true value. This means the integer zero is evaluated to true.
if (1 - 1) {
// okay, 0 is true!
}
while (foo() || bar()) {
doBaz();
}
for (i = 0; i < len; ++i) {
update(i);
}
for (entry: container) {
}
spawn thread_name {
... // statements block.
for (i = 0; i < n; ++i) {
... // do something.
}
foo();
}
// or...
spawn thread_name[2] { // create two threads.
... // do something.
}
wait thread_name; // wait threads called "thread_name".
spawn t {
critical {
doSomeCriticalOperation(); // here, you can read a file or a standard stream.
}
}
Syntax error
On syntax error, the compilation is aborted.
Runtime error
Some internal methods can throw exceptions.
Throwing exception
try {
throw 'test';
} catch (e) {
println(e); // test
}