declaration → classDecl
| funDecl
| varDecl
| statement ;
statement → exprStmt
| forStmt
| ifStmt
| printStmt
| returnStmt
| whileStmt
| block ;
block → "{" declaration* "}" ;var name = "Alice";
var age = 25;
print name + " is " + age + " years old.";Output:
Alice is 25 years old.
var x = 10;
if (x > 5) {
print "x is greater than 5";
} else {
print "x is 5 or less";
}Output:
x is greater than 5
var count = 3;
while (count > 0) {
print count;
count = count - 1;
}
print "Done!";Output:
3
2
1
Done!
for (var i = 0; i < 5; i = i + 1) {
print i;
}Output:
0
1
2
3
4
fun greet(name) {
print "Hello, " + name + "!";
}
greet("Alice");Output:
Hello, Alice!
fun makeCounter() {
var count = 0;
fun increment() {
count = count + 1;
print count;
}
return increment;
}
var counter = makeCounter();
counter(); // 1
counter(); // 2Output:
1
2
class Person {
init(name, age) {
this.name = name;
this.age = age;
}
greet() {
print "Hello, my name is " + this.name;
}
}
var alice = Person("Alice", 25);
alice.greet();Output:
Hello, my name is Alice
class Animal {
speak() {
print "Some generic animal sound";
}
}
class Dog < Animal {
speak() {
print "Woof!";
}
}
var pet = Dog();
pet.speak(); // Woof!Output:
Woof!