File size: 5,278 Bytes
d086025 | 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 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | # Dragon language guide
A usage-level tour of Dragon syntax. Every snippet here can be pasted into a
`.dgn` file and run with `dragon file.dgn`. The complete programs in
[`assets/examples/`](assets/examples/) cover the same ground in runnable form.
---
## Program structure
Statements end with a newline; blocks use braces. A program is usually a set of
function/class declarations followed by a call to `main()`:
```dragon
func main() {
showln("Hello, Dragon!")
}
main()
```
There is no `public`/`static` ceremony, and no semicolons are required.
## Variables and types
Variables are dynamically typed and assigned without a keyword. Booleans are
capitalised literals; `None` is the empty value.
```dragon
name = "Dragon"
version = 1.0
age = 5
is_awesome = True
nothing = None
```
`const` declares a value that cannot be reassigned:
```dragon
const GREETING = "Hello"
```
Check a value's type with `typeof()`, and convert with `str()`, `int()`,
`float()`, `bool()`.
## Output
```dragon
show("no newline") // print without a trailing newline
showln("with newline") // print a line
```
`show` / `showln` accept any number of arguments and separate them with a space.
## Strings and interpolation
Double-quoted strings support escapes; backtick strings support `{expression}`
interpolation (also written `${expression}`):
```dragon
showln(`Welcome to ${name} v${version}!`)
showln(`${a} + ${b} = ${a + b}`)
```
`format()` provides printf-style control over output:
```dragon
showln(format("Pi rounded to 2 places: {:.2f}", 3.14159))
showln(format("Padded number: [{:>6}]", 42))
```
String methods: `trim()`, `upper()`, `lower()`, `split(sep)`,
`contains(sub)`, `replace(old, new)`, plus concatenation with `+`.
## Numbers
`+ - * / %` with normal precedence, and comparison operators
`== != < <= > >=`.
## Control flow
```dragon
if n < 0 {
showln("negative")
} elif n == 0 {
showln("zero")
} else {
showln("positive")
}
while countdown > 0 {
countdown = countdown - 1
}
do {
tries = tries + 1
} while tries < 3
for x in [1, 2, 3] { } // over a list
for i, v in list { } // index and value
for k, val in map { } // key and value
for i in math.range(5) { } // range (start, stop, step)
switch day {
case "Sat":
showln("weekend")
default:
showln("weekday")
}
grade = score >= 90 ? "A" : "C" // ternary
```
`break` exits a loop, `continue` skips to the next iteration.
## Functions
```dragon
func greet(name, greeting = "Hello") { // default parameter
return `${greeting}, ${name}!`
}
func sum_all(...numbers) { // rest parameter
total = 0
for n in numbers { total = total + n }
return total
}
square = (x) => x * x // lambda
add = (a, b) => a + b
```
Functions are values: they can be stored in variables, kept in lists, and
passed to other functions (for example to `thread.spawn`).
## Collections
```dragon
numbers = [5, 3, 8, 1, 9, 2]
numbers.push(7)
len(numbers)
numbers.map((x) => x * 2)
numbers.filter((x) => x % 2 == 0)
numbers.reduce((acc, x) => acc + x, 0)
numbers.sort()
person = { name: "Ada Lovelace", role: "Mathematician", year: 1815 }
person.name // field access
person.set("field", "CS") // add/replace a key
for key, value in person { }
```
Index with `list[0]`, nest freely, and iterate with `for ... in`.
## Classes
```dragon
class Animal {
func init(name, sound) { // constructor
this.name = name
this.sound = sound
}
func speak() {
return `${this.name} says ${this.sound}`
}
}
class Dog extends Animal {
func init(name) {
super.init(name, "Woof") // call the parent constructor
this.tricks = []
}
func describe() { // override a parent method
return `I am ${this.name}, a good dog.`
}
}
rex = new Dog("Rex")
rex.speak()
```
`this` refers to the instance, `super` to the base class, and `new` constructs
an object. `typeof(rex)` returns the class name.
## Errors
```dragon
try {
if b == 0 {
raise "Cannot divide by zero!"
}
result = a / b
} catch (err) {
showln(`error: ${err}`)
} finally {
showln("(cleanup)")
}
```
`raise` throws the given value; `catch` binds it; `finally` runs in all cases.
A `raise` is handled by a `try`/`catch` in the **same function** it is raised
from, so validate arguments before calling out to another function when you
want one enclosing handler to cover them.
## Modules
`import` loads a standard module, either as a statement or with the module
object bound to its name:
```dragon
import "math"
import math
import json
showln(math.sqrt(144))
showln(json.encode({ ok: True }))
```
See [`standard-library.md`](standard-library.md) for the available modules.
## Async and threads
Dragon has built-in `async` / `await` support for concurrent code, and the
`thread` module spawns concurrent work by handing a function value a list of
arguments:
```dragon
import "thread"
func worker(id) {
sleep(0.5)
showln("Task", id, "done")
}
for i in math.range(5) {
thread.spawn(worker, [i])
}
showln("All tasks started")
```
`sleep(seconds)` pauses the current thread.
|