# 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.