raz / examples / Settings.raz

65 lines · 1.8 KiB · raw · history · last change e0d008cd

1(* Strings: reads settings from a text of its own, written as a raw
2 string that keeps the indent of the code around it. Each line is a
3 name, =, and a value; # starts a comment. Str takes the lines apart
4 without copying them, and a match on a string picks what each name
5 sets. *)
6module Settings;
7import Out, Fmt, Str, Math;
8
9const
10 Text = `
11 # a window
12 title = raz \ settings
13 width = 80
14 Height=24
15 scale = 1.5
16 colour = "green"
17 depth
18 `;
19
20var
21 title: []const U8;
22 width, height: I64;
23 scale: F64;
24
25(* One setting: false if the name isn't known, or its value is wrong. *)
26proc setting(name, value: []const U8): BOOL;
27var ok: BOOL; lower: [16]U8;
28begin
29 if LEN(name) > LEN(lower) then return false; end;
30 COPY(lower, name);
31 Str.lower(lower[0..LEN(name)]);
32 ok := true;
33 match lower[0..LEN(name)] of
34 | "title": title := value;
35 | "width": width, ok := Str.toInt(value);
36 | "height": height, ok := Str.toInt(value);
37 | "scale": scale, ok := Math.toReal(value);
38 | else: ok := false;
39 end;
40 return ok;
41end;
42
43proc main*;
44var line, rest, name, value: []const U8; more, found: BOOL; n: INT;
45begin
46 rest := Text;
47 more := true;
48 while more do
49 line, rest, more := Str.cut(rest, "\n");
50 line, _, _ := Str.cut(line, "#");
51 line := Str.trim(line);
52 if LEN(line) > 0 then
53 INC(n);
54 name, value, found := Str.cut(line, "=");
55 if not found or not setting(Str.trim(name), Str.trim(value)) then
56 Fmt.print("line {}: {}\n", [Fmt.int(n), Fmt.str(line)]);
57 end;
58 end;
59 end;
60 Fmt.print("{}: {} by {}, at {}\n", [Fmt.str(title), Fmt.int(width), Fmt.int(height),
61 Fmt.real(scale, 1)]);
62 Out.int(Str.chars("naïve")); Out.str(" characters in naïve\n");
63end;
64
65end Settings.