aboutsummaryrefslogtreecommitdiff
path: root/examples/struct_closure_opt.zc
blob: 254ff0747a5aee44e29e5825d46c108a98b4e287 (plain) (blame)
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
namespace;
include rt;

// struct methods, closures and ownership in one file, written so the
// compiler's hints have something to say about it. it runs as it is.

struct point {
	let x, y;

	// methods get a hidden first parameter called this
	fn dist(other) {
		let dx = this.x - other.x;
		let dy = this.y - other.y;
		return dx * dx + dy * dy;
	}
}

void sink(.d p) { rt.free(p); return; }

fn features() {
	// a closure shares the variables it captures
	let base = 100;
	let add = fn(a, b) { return a + b + base; };
	let total = add(10, 20);

	let p1 = rt.new(point);
	p1.x = 5; p1.y = 12;
	let p2 = rt.new(point);
	p2.x = 0; p2.y = 0;

	// made and given away on the next line, so it never needed a name
	let tmp = rt.new(2);
	sink(tmp);

	// allocated again on every pass of the loop
	let i = 0;
	while (i < 3) {
		let scratch = rt.new(10);
		scratch[0] = i;
		sink(scratch);
		i++;
	}

	return total + p1.dist(p2);
}

void main() {
	rt.put_n(features()); rt.put_c(10);
	return;
}