Jump to content

An Introduction to Dragon/Lessons/Variables

From Wikibooks, open books for an open world

Variables

[edit | edit source]

Variables in Dragon require no type declaration or keyword — assignment creates them:

name = "Dragon"
version = 1.0
age = 5
is_awesome = True

Dynamic Typing

[edit | edit source]

A variable's type is determined by the value currently assigned to it, and can change over the variable's lifetime:

x = 10        // x is a number
x = "ten"     // now x is a string
x = [1, 2, 3] // now x is a list

Use typeof() to inspect a value's current type at run time:

showln("typeof age:", typeof(age))

Weakly Typed

[edit | edit source]

Dragon is weakly typed: operators will implicitly convert between compatible types rather than raising an error, so mixing numbers and strings in certain expressions is generally permitted rather than rejected outright.

Deep Copy

[edit | edit source]

Collections (lists and maps) are reference types by default. When a genuinely independent copy is required — so that modifying the copy does not affect the original — Dragon provides deep-copy semantics for collections rather than only copying the reference. Always check whether you need a reference or a copy before assigning a list or map to a new variable.

Constants

[edit | edit source]

Values declared with const cannot be reassigned after they are set:

const GREETING = "Hello"
showln(GREETING + ", World!")

typeof() and Type Conversions

[edit | edit source]
showln("str(age):", str(age))
showln("int(\"42\"):", int("42"))

str(), int(), and related conversion functions coerce a value to the requested type.

String Interpolation

[edit | edit source]

Backtick strings support ${expr} placeholders, evaluated and inserted at run time:

a = 10
b = 3
showln(`${a} + ${b} = ${a + b}`)

Formatting Output

[edit | edit source]

format() gives fine-grained control over how a value is rendered:

pi = 3.14159
showln(format("Pi rounded to 2 places: {:.2f}", pi))
showln(format("Padded number: [{:>6}]", 42))