| 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. *) |
| 6 | module Settings; |
| 7 | import Out, Fmt, Str, Math; |
| 8 | |
| 9 | const |
| 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 | |
| 20 | var |
| 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. *) |
| 26 | proc setting(name, value: []const U8): BOOL; |
| 27 | var ok: BOOL; lower: [16]U8; |
| 28 | begin |
| 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; |
| 41 | end; |
| 42 | |
| 43 | proc main*; |
| 44 | var line, rest, name, value: []const U8; more, found: BOOL; n: INT; |
| 45 | begin |
| 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"); |
| 63 | end; |
| 64 | |
| 65 | end Settings. |