You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/language_reference.md
+80Lines changed: 80 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -226,3 +226,83 @@ Precedence of various operators is defined as follows *(from highest to lowest)*
226
226
_x = 5 / "4"; // ERR: Cannot use operator '/' with 'number' and 'string'
227
227
_x = "20" / 4; // ERR: Cannot use operator '/' with 'string' and 'number'
228
228
```
229
+
230
+
## Control structures
231
+
You can control the flow of your program by using several types of statements Primi provides.
232
+
233
+
### *if* construct
234
+
235
+
The *`if`* construct *- as in all other programming languages -* allows you to dynamically branch your program based on some runtime conditions.
236
+
237
+
#### Examples
238
+
239
+
```
240
+
a = true;
241
+
if (a) {
242
+
b = 1;
243
+
}
244
+
// b == 1
245
+
```
246
+
247
+
```
248
+
a = false;
249
+
b = true;
250
+
c = 5;
251
+
if (a or b) {
252
+
d = 1;
253
+
if (d > c) {
254
+
e = d + c;
255
+
}
256
+
}
257
+
// d == 1, e == 6
258
+
```
259
+
260
+
### *for* construct
261
+
262
+
The *`for`* construct allows you to iterate over a value that supports it *(`array` or `string` values)* while performing a task on that collection's single item.
263
+
264
+
#### Examples
265
+
266
+
```
267
+
txt = "123456789";
268
+
result = [];
269
+
for (n in txt) {
270
+
if (5 > n.to_number() > 0) {
271
+
result.push(n);
272
+
}
273
+
}
274
+
// result == [0: "1", 1: "2", 2: "3", 3: "4"]
275
+
```
276
+
277
+
```
278
+
prices = [100, 200, 300, 600, 1200];
279
+
sentence_template = "This costs {} units of money!";
280
+
results = [];
281
+
for (price in prices) {
282
+
results.push(sentence_template.format(price));
283
+
}
284
+
// results == [
285
+
// 0: "This costs 100 units of money!",
286
+
// 1: "This costs 200 units of money!",
287
+
// 2: "This costs 300 units of money!",
288
+
// 3: "This costs 600 units of money!",
289
+
// 4: "This costs 1200 units of money!"
290
+
// ]
291
+
```
292
+
293
+
*Note: The flow of program inside the `for` cycle can be controlled further by using the `continue` and `break` statements.*
294
+
295
+
### *while* construct
296
+
297
+
The *`while`* construct does a thing if a specified condition is met (ie. if the expression inside has a *truthy* value).
298
+
299
+
```
300
+
c = 0;
301
+
while (c < 100) {
302
+
total = total + c;
303
+
c = c + 1;
304
+
}
305
+
// total == 4950
306
+
```
307
+
308
+
*Note: The flow of program inside the `while` cycle can be controlled further by using the `continue` and `break` statements.*
0 commit comments