# Wren Tutorial: Core to Advanced
## Basics
Wren: OOP scripting. Classes: `class Name { construct new(args) { _vars } methods }`. Inherit: `is Super`. Fn: `Fn.new { |args| body }`. Import: `import "mod" for Items`. Vars: `var x = val`. Loops: `for (i in seq) { }`, `while (cond) { }`. Conditionals: `if/else`. Errors: `Fiber.abort("msg")`.
Example:
```
class Point {
construct new(x, y) { _x = x; _y = y }
x { _x }
}
var p = Point.new(1, 2)
System.print(p.x) // 1
```
## Core Classes
- **Bool/Fiber/Fn/Null/Num**: Base.
- **Sequence**: `all/any(f)`, `contains(el)`, `count/f`, `each(f)`, `isEmpty`, `map(f)`, `skip/take(n)`, `where(f)`, `reduce/acc+f`, `join/sep`, `toList`.
- **String**: `bytes/codePoints` (seqs), `split(delim)`, `replace(from/to)`, `trim/chars/start/end`, `*(n)`.
- **List**: `addAll(other)`, `sort/comparer` (quicksort), `toString`, `+/ *(other/n)`.
- **Map**: `keys/values` (seqs), `toString`, `iteratorValue``MapEntry(key/val)`.
- **Range**: Seq empty.
- **System**: `print/obj/All`, `write/obj/All`, `clock`.
## Meta/Random
- **Meta**: `getModuleVariables(mod)`, `eval(src)`, `compileExpression/src`.
- **Random**: `new/seed`, `float/int/range`, `sample(list/n)`, `shuffle(list)`.
## IO/OS
- **File**: `read/write(path)`, `exists/delete`.
- **Directory**: `list/exists/mkdir/rmdir/delete(path)`.
- **Stdin/Stdout**: `readLine`, `flush`.
- **Process**: `args`, timed exec.
## Fibers/Scheduler/Timer
- Fiber: `new { body }`, `call/try`.
- Scheduler: `add { body }` (runs on IO).
- Timer: `sleep(ms)` (suspends).
## Modules/Examples
- **Argparse**: `new(desc)`, `addArgument(opt, {help/default/action/type})`, `parseArgs(args) → map`.
- **Base64**: `encode/decode(str)`, `encodeUrl/decodeUrl`.
- **Bytes**: `fromList/toList`, `length/concat/slice`, `xorMask(payload/mask)`.
- **Crypto**: `randomBytes(n)/Int(min,max)`; Hash: `md5/sha1/sha256(str)`, `toHex`.
- **Dataset**: `memory()["table"]`: `insert(map) → uid`, `all/find(query)/findOne`, `update/delete(uid)`, `columns/tables`.
- **Datetime**: `now/fromTimestamp`, components, `format(fmt)`, `+/- Duration` (fromHours/etc, seconds/+/-/*).
- **Dns**: `lookup(host,4/6) → [ips]`.
- **Pathlib**: `new(path)`, `exists/isDir/File`, `expanduser/glob/rglob`, `iterdir/joinpath/match/mkdir`, `name/stem/suffix/es`, `parent/parents/parts`, `readText/writeText/unlink`, `relativeTo/rename/walk`, `withName/Stem/Suffix`.
- **Regex**: `new(pat/flags)`, `test/replace/All/split`.
- **Signal**: Constants (SIGINT=2, etc.).
- **Sqlite**: `memory()`: `execute(sql,params)`, `lastInsertId/changes`, `query → rows`.
- **String Utils**: `toLower/Upper/hexEncode/Decode/repeat/padLeft/Right/escapeHtml/Json/urlEncode/Decode`.
- **Strutil**: As above.
- **Subprocess**: `run(cmd/args) → ProcessResult(success/exitCode/stdout)`.
- **Tempfile**: `gettempdir/mkdtemp/stemp/temp(suffix/prefix/dir)`, NamedTemporaryFile/TemporaryDirectory (name/write/read/close/delete/use/cleanup).
- **Uuid**: `v4() → str`, `isValid/V4`.
- **Wdantic**: Schema: `new({field: Field.type(opts)})`, `validate(data) → ValidationResult(isValid/errors/data)`; Validators: email/domain/etc.
- **Web**: Client: `parseUrl_(url) → {scheme/host/port/path}`; Request: `new_(method/path/query/headers/body/params/files)`, `header/json/cookies/form`; Response: `text/html/json/redirect/new(status/body/header/cookie/build)`; Router: `new()`, `get/post/etc(path,handler)`, `match(method/path) → {handler/params}`; SessionStore: `create/get/save/destroy`.
- **Websocket**: `computeAcceptKey(base64)`, Message: `new_(opcode/payload/fin)`, `isText/etc`; Server: `bind/accept/receive/sendBinary/close`.
## Tests/Benchmarks
- Fib: Recursive fib(28).
- Nbody: Solar system sim (bodies, energy, advance).
- Demos: Animals game (tree nodes), chat server (TCP fibers), browser auto (WS commands), etc.
## Usage
Import modules, use classes/fns. Run: Compile/eval via Meta. Async: Fibers + Scheduler/Timer.
## Feature-Packed Example
```
import "io" for File, Directory, Stdin
import "timer" for Timer
import "scheduler" for Scheduler
import "random" for Random
import "meta" for Meta
import "os" for Process
class Demo is Sequence {
construct new() { _list = [1,2,3] }
iterate(i) { _list.iterate(i) }
iteratorValue(i) { _list.iteratorValue(i) * 2 }
}
var rand = Random.new()
System.print(rand.int(10)) // Random num
var seq = Demo.new()
System.print(seq.map { |x| x + 1 }.toList) // [3,5,7]
Scheduler.add {
Timer.sleep(100)
System.print("Async fiber")
}
var modVars = Meta.getModuleVariables("io")
System.print(modVars) // Module vars
var file = "temp.txt"
File.create(file) { |f| f.writeBytes("data") }
System.print(File.read(file)) // data
File.delete(file)
var sub = Subprocess.run("echo hello")
System.print(sub.stdout.trim()) // hello
System.print(Process.args) // Args
```