-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbasic.lox
153 lines (119 loc) · 2.39 KB
/
basic.lox
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// Data types
// Booleans
true; // Not false.
false; // Not *not* false.
// Numbers
1234; // An integer.
12.34; // A decimal number.
// Strings
"I am a string";
""; // The empty string.
"123"; // This is a string, not a number.
// Nil
nil; // This is nil/null
// Expressions
// Arithmetics
var me = nil;
var add = 23 + 41;
var subtract = 13 - 4;
var multiply = 13 * 4;
var divide = 62 / 2;
var negateMe = -add;
// Comparison and equality
var less = add < subtract;
var more = multiply > divide;
var equality = add == subtract;
var inequality = multiply != divide;
// Unary logical operator
var isTrue = !false;
var isFalse = !true;
// Binary logical operator
var andTrue = isTrue and !isFalse;
var orFalse = !isTrue or isFalse;
// Precedence and grouping
var min = 14;
var max = 22;
var average = (min + max) / 2;
// Variables
// Can reassign an existing variable
min = 5;
// Printing
print average;
// Blocks
{
print "This is a new block";
var x = 15;
}
print "`x` isn't available in this scope";
// Control flow
// If branching
if (average > 5) {
print "yes";
} else {
print "no";
}
// While loops
var a = 1;
while (a < 10) {
print a;
a = a + 1;
}
// For loops
for (var i = 1; i < 10; i = i + 1) {
print i;
}
// Functions
fun printSum(a: number, b: number): void {
print a + b;
}
fun returnSum(a: number, b: number): number {
return a + b;
}
// Closures
fun identity(a: (number, number) => number): (number, number) => number {
return a;
}
print identity(returnSum)(1, 2); // prints "3";
fun outerFunction(): void {
fun localFunction(): void {
print "I'm local!";
}
localFunction();
}
fun returnFunction(): () => void {
var outside = "outside";
fun inner(): void {
print outside;
}
return inner;
}
var fn = returnFunction();
fn();
// Classes WIP
class SuperClass {
a: number
}
class SubClass < SuperClass {
// Nested class
nested: NestedClass
}
class NestedClass {
field: string
method(): string {
return "execute this";
}
}
// Constructor call
var x = SubClass();
// Assigning nil to a class type
var nilTest = SubClass();
nilTest = nil;
// Accessing members of a class
var value = x.nested.method() + "wasd";
print value;
// Accessing members of a super class
var superValue = x.a;
print superValue;
// Assigning a subclass to a super class
var superType: SuperClass = x;
print superType.a;