# Katton scripting language - summary

this is a summary of everything in the wiki so that people who REALLY want to script things but don't want to actually like "learn it" or are having trouble with it can feed this into AI to get help and stuff like that

---

you are writing scripts in **Katton**, a sandboxed scripting language for a minecraft paper plugin. scripts are plain text `.kat` files. this document is the complete syntax + api reference. follow it exactly. Katton has no type annotations, no `while` loop, and a small, fixed set of built in methods/objects

when asked to write a Katton script, use ONLY what's documented below. if something seems impossible with this API, say so instead of guessing a method name

---

## 1. syntax basics

- blocks use `{ }`, never indentation. every `{` needs a matching `}`
- comments: `// line comment` and `/* block comment */`
- strings: double quoted only. escapes: `\n` `\t` `\"` `\\`
- **no type annotations anywhere** `function f(a, b)` not `function f(a: Type, b: Type)`
- a script file is just a flat list of top level declarations: `val`/`var`, `function`, and annotated functions (`@Katton.command`, `@Katton.listen`)
- top level `val`/`var` are evaluated once at compile time, and are shared across every function in that script (this is how you share state between a command and a listener, or between a `Katton.every` callback and the rest of the script)

```csharp
val maxPlayers = 8 // immutable
var currentRound = 0 // mutable

function helper(x) { // plain function
    return x * 2
}

@Katton.command(name = "start", permission = "admin")
function startGame(sender, args) { ... }

@Katton.listen("player_join")
function onJoin(event) { ... }
```

## 2. types

there are exactly five runtime types, plus `null`. no separate int/float, everything is a decimal number

| type | example |
|---|---|
| number | `5`, `3.5`, `-2` |
| string | `"hello"` |
| boolean | `true`, `false` |
| list | `["a", "b", "c"]` (ordered, mutable) |
| map | `{ "key": "value" }` (insertion ordered, mutable) |
| null | `null` |

`val` = immutable (reassigning is a runtime error). `var` = mutable. use `var` for counters/flags/state, `val` for everything else

## 3. operators

```csharp
5 + 3   5 - 3   5 * 3   5 / 3   5 % 3   -5 // arithmetic / and % by 0 is a runtime error
"Score: " + 10 // "+" concatenates when either side is a string. this also auto stringifies the other side
5 == 5  5 != 3  5 < 10  5 <= 5  5 > 10  5 >= 5 // == works on any type including strings/lists
true && false   true || false   !true // boolean logic
= += -= *= /= // assignment operators (var only)
```

## 4. control flow

`if`/`else`. braces are always required, even for one statement:

```csharp
if (player.health < 5) {
    player.sendMessage("&clow health!")
} else if (player.health < 10) {
    player.sendMessage("&egetting low...")
} else {
    player.sendMessage("&ayoure ok :D")
}
```

`when`: compares one value top to bottom, like a switch:

```csharp
when (color) {
    "red" -> { player.sendMessage("&cred team!") }
    "blue" -> { player.sendMessage("&9blue team!") }
    else -> { player.sendMessage("&7unknown team") } // optional
}
```

`return`: a function with no `return` returns `null`. a bare `return` is valid to exit early. almost always use an early `return` at the top of event listeners and scheduled callbacks to bail out when a condition doesn't apply

## 5. loops

**there is no `while` loop.** use ranges or recursion instead

```csharp
for (i in 0..9) { ... } // ascending, INCLUSIVE both ends -> 0,1,...,9
for (i in 10 downTo 1) { ... } // descending, inclusive -> 10,9,...,1
for (color in ["red","blue"]) { ... } // iterate a list
for (key in { "red": 1 }) { ... } // iterate a map -> iterates KEYS
for (p in Katton.players.all()) { ... } // iterate players
break // exits the loop
continue // skips to next iteration
```

## 6. functions

three kinds:

```csharp
// 1. plain helper. any number of params, call it like anything else
function addTax(price, rate) {
    return price + (price * rate)
}

// 2. command handler. MUST take exactly (sender, args), no more no less
@Katton.command(name = "heal", permission = "admin" | "creative" | "all")
function healSender(sender, args) {
    sender.setHealth(20)
}

// 3. event listener. MUST take exactly (event)
@Katton.listen("player_death")
function onDeath(event) {
    event.player.sendMessage("&cyou died!")
}
```

`@Katton.command` rules:
- `name` must be lowercase letters/numbers/underscores/hyphens only, and unique across that script (and across every other script you own)
- `permission` is exactly `"admin"` (only the current admin), `"creative"` (admin + creative- ode players), or `"all"` (admin + creative/spectator/survival/adventure, i.e. everyone)
- `args` is a list of strings (everything typed after the command name)

`@Katton.listen` takes exactly one event name string. see the event list in section 11

## 7. strings (methods on any string value)

```csharp
text.toUpperCase()   text.toLowerCase()   text.trim()
text.length()
text.contains(sub)   text.startsWith(sub)   text.endsWith(sub)
text.replace(old, new)
text.split(delimiter) // -> list of strings
```

## 8. lists (ordered, mutable)

```csharp
val colors = ["red", "blue", "lime"]
colors[0] // index access
colors[0] = "green" // index assignment

list.append(x)   list.add(x) // same thing, adds to end
list.remove(x) // removes first matching VALUE
list.removeAt(index) // removes by index
list.contains(x)
list.size()      list.size // method or property, both work
list.isEmpty()
list.get(index) // same as list[index]
list.clear()
```

## 9. maps (insertion ordered, mutable)

```csharp
val scores = { "red": 1, "blue": 2 }
scores["red"] // key access
scores["green"] = 0 // adds/replaces a key

map.get(key)
map.put(key, value)   map.set(key, value) // same thing
map.remove(key)
map.containsKey(key)
map.size()
map.isEmpty()
map.keys() // -> list
map.values() // -> list
map.clear()
```

## 10. math namespace

```csharp
Math.abs(-5) // 5
Math.min(a, b)   Math.max(a, b)
Math.clamp(value, min, max)
Math.floor(x)   Math.ceil(x)   Math.round(x)
Math.randomInt(min, max) // inclusive whole number
Math.randomDecimal(min, max) // inclusive decimal
Math.sin(60) // ~0.866
Math.cos(60) // ~0.5
```

## 11. random picking

```csharp
Katton.pick(list) // one random element, or null if list is empty
Katton.pickMany(list, n) // up to n UNIQUE random elements (fewer if list is smaller)
```

## 12. scheduling: `Katton.after` / `Katton.every` / `Katton.cancel`

```csharp
val taskId = Katton.after(duration) { ... } // runs ONCE after duration
val taskId = Katton.every(duration) { ... } // runs REPEATEDLY forever until cancelled
Katton.cancel(taskId) // stop a task you stored the id of
```

duration literals: `20.ticks` (= 1 second), `5.seconds`, `2.minutes`. also works on variables: `delay.seconds`

- both return a task id (a number). **store it in a top level `var`** if you'll need to cancel it later from a different function or from inside the callback itself (self cancelling countdowns for example)
- don't nest `Katton.after` inside `Katton.every` unless you really mean to spawn a new independent delayed task every single tick of the outer timer - it stacks up fast
- tasks auto cancel when: `/katton stop` is run, the script is reimported or deleted, you stop being the admin, the server restarts, or a person with op forcibily stops it

```csharp
var countdown = 3
var countdownTaskId = 0

@Katton.command(name = "startcountdown", permission = "admin")
function startCountdown(sender, args) {
    countdown = 3
    countdownTaskId = Katton.every(1.seconds) {
        for (p in Katton.players.all()) { p.sendTitle("&e" + countdown, "") }
        countdown = countdown - 1
        if (countdown < 0) { Katton.cancel(countdownTaskId) }
    }
}
```

## 13. `Katton.vars` (persistent state)

two namespaces, each giving you a "bucket" with the same four methods:

```csharp
Katton.vars.script // one shared bucket for the whole script
Katton.vars.player(uuid) // one bucket PER PLAYER, keyed by their uuid string

bucket.get(name) // null if never set
bucket.set(name, value) // accepts string/number/boolean/list/map
bucket.increment(name, by = 1) // atomic, returns the NEW value
bucket.decrement(name, by = 1) // atomic, returns the NEW value
```

```csharp
val kills = Katton.vars.player(event.player.uuid).increment("kills")
```

- each individual bucket caps out at **100 distinct variable names** (overwriting an existing name is allowed only brand new names count). don't generate unique variable names in a loop instead reuse a fixed set, or store a list/map as a single value instead
- persists across restartsand cleared automatically when the script is deleted

## 14. `Katton.log`

```csharp
Katton.log.info(msg)   Katton.log.warn(msg)   Katton.log.error(msg)
```

sends chat messages to **only you** (the script owner), regardless of who triggered the code. use this for debugging, it's never for messaging players (use `player.sendMessage` for that)

## 15. `Katton.players` (selectors)

automatically scoped to your own world/preset there is no manual world filtering needed

```csharp
Katton.players.all() // everyone in your world
Katton.players.survival() // survival + adventure mode
Katton.players.spectator()
Katton.players.creative()
```

## 16. `item` - `Katton.item(...)` and item values

```csharp
val sword = Katton.item(material, amount = 1) // material = case insensitive vanilla Material name (https://jd.papermc.io/paper/1.21.11/org/bukkit/Material.html)
```

methods:

```csharp
item.setName(text) // supports & color codes
item.setLore(["line1","line2"]) // list of strings, one per line
item.setTag(key, value) // value is always stored/read back as a STRING
item.getTag(key) // null if never set. ALWAYS null check
item.enchant(name, level) // level 1-5, unknown enchant name = runtime error
item.clone()
```

## 17. `player` get one from `Katton.players.*`, a command's `sender`, or `event.player`

properties:

```csharp
player.name   player.uuid   player.world
player.location // { x, y, z, yaw, pitch, world }
player.health   player.game_mode // "survival"|"creative"|"adventure"|"spectator"
player.is_sneaking   player.is_sprinting
player.facing // 1=down 2=up 3=north 4=south 5=west 6=east
player.tool   player.offhand_tool // item values for held items (air if empty)
```

methods:

```csharp
player.sendMessage(text)
player.sendTitle(title, subtitle = "")
player.sendActionBar(text)
player.teleport(location)
player.give(item)
player.setTool(item)          player.setOffhandTool(item) // replaces held item, doesn't add to inventory
player.clearInventory()
player.playSound(sound, volume = 1, pitch = 1)
player.setGlowing(glowing = true)
player.setMovementSpeed(speed)   player.resetMovementSpeed() // vanilla default ~0.1
player.setJumpStrength(strength)   player.resetJumpStrength() // vanilla default ~0.42
player.setInvulnerable(invulnerable = true)
player.launchForward(horizontal, vertical) // max magnitude 6 each
player.shootProjectile(projectile, speed) // max speed 6
```

allowed `shootProjectile` projectile names: `arrow`, `spectral_arrow`, `snowball`, `egg`, `ender_pearl`, `fireball`, `ghast_fireball`, `small_fireball`, `dragon_fireball`, `wither_skull`, `shulker_bullet`, `trident`, `experience_bottle`

note: `player.setHealth(health)` also exists as a method (clamped 0..max_health)

## 18. `entity` from `world.entities` or `world.spawnEntity(...)` (players NOT included)

properties:

```csharp
entity.uuid   entity.type   entity.is_valid
entity.location
entity.health   entity.max_health   entity.yaw   entity.pitch // living entities only
entity.tags // list of scoreboard tag strings
```

check `entity.is_valid` before using a entity reference later (example: inside a `Katton.after` callback). everything will throw if it's no longer valid, except `is_valid`/`uuid` themselves

methods:

```csharp
entity.setHealth(health)            entity.kill()
entity.setDisplayName(text)         entity.teleport(location)
entity.setGlowing(glowing = true)
entity.addTag(tag)   entity.removeTag(tag)   entity.hasTag(tag)
entity.setMovementSpeed(speed)      entity.setJumpStrength(strength) // living entities only
entity.setItem(item) // item display entities only
entity.setTeleportDuration(ticks) // display entities only, clamped 0-59
```

## 19. `world` - `Katton.world()`

properties:

```csharp
world.players // list of player values
world.entities // list of entity values (no players)
```

methods:

```csharp
world.spawnEntity(type, location) // -> entity value
world.setBlock(location, material)
world.getBlock(location) // read-only, returns material name string
world.fillBlocks(from, to, material) // inclusive box, capped at 4096 blocks per call
world.playSound(sound, location, volume = 1, pitch = 1) // heard by everyone, vs player.playSound (one person)
```

`spawnEntity`/`setBlock`/`fillBlocks` share ONE rate limit and will throw a runtime error telling you to slow down if you go too fast. don't spam these

## 20. `event` the parameter in every `@Katton.listen` handler

```csharp
event.player // player value, where applicable
event.item // FULL item value (not a string!) where applicable. supports .getTag() etc
event.block // material name STRING, where applicable
event.entity // type name STRING, where applicable
event.projectile // type name STRING, where applicable
event.cancel() // cancels the action if cancellable. returns true/false. always safe to call
event.clearDrops() // clears the drops from when a player dies
```

always null check `event.item` and `event.block` (example: empty hand = null item, clicking air = null block)

## 21. full event list (these are the ONLY valid names for `@Katton.listen`)

| event name | properties | fires when |
|---|---|---|
| `player_join` | `event.player` | player enters the arena/their preset (NOT server connect) |
| `player_quit` | `event.player` | player leaves the arena/their preset (NOT server disconnect) |
| `player_death` | `event.player` | a player dies |
| `player_respawn` | `event.player` | a player respawns |
| `player_interact` | `event.player`, `event.item`, `event.action`, `event.block` | interacting with a block (example: chest) |
| `player_leftclick` | `event.player`, `event.item` | left click (air or block) |
| `player_rightclick` | `event.player`, `event.item` | right click (air or block) |
| `block_break` | `event.player`, `event.block` | breaking a block (cancellable) |
| `block_place` | `event.player`, `event.block` | placing a block (cancellable) |
| `entity_death` | `event.entity`, `event.killer` | any entity (including players) dying |
| `item_drop` | `event.player`, `event.item` | dropping an item (cancellable) |
| `item_pickup` | `event.player`, `event.item` | picking up an item (cancellable) |
| `player_interact_entity` | `event.player`, `event.entity` | right-clicking an entity |
| `projectile_hit` | `event.player`, `event.projectile`, `event.entity`, `event.block` | a projectile hits something (entity/block null depending on which) |
| `player_shoot_bow` | `event.player`, `event.item`, `event.projectile` | a player shoots a bow |

cancellable events: interactions, block break/place, item drop/pickup. `player_join`/`player_quit`/etc are not cancellable (`.cancel()` just returns `false`)

## 22. `Katton.makeAdminExecuteCommand`

```csharp
Katton.makeAdminExecuteCommand(command) // makes the CURRENT admin run a command, returns a result string
```

- only works in the actual game (arena), not in custom presets (besides worldedit commands)
- the command's first word must be on the allow list below (arguments after it are mostly unrestricted)

allow listed roots:
```
border, bring, bringall, broadcast, cleareffects, countdown, stopcd, crafting, creative,
cylinder, day, deathmessages, difficulty, togglesuicide, chatcooldown, dropping, falldamage,
freeze, hardcore, hardcorebeds, heal, healall, hideplayers, viewplayers, highlight, hunger,
iframes, interacting, keepinv, kill, killall, killmobs, mobdamage, mobspawning, mutechat,
mutespectators, nametags, naturalregen, night, oldcombat, pickup, platform, pve, pvp,
random, randomitems, reducedf3, respawntimer, setskin, setspawnpoint, spectator, survival,
team, title, tnt, winblock, autopickup, adminlock, to, goto, poll, placing, breaking,
building, clearplayer, blockattributes, elytradamage, reminder, autosmelt, hidehates, cyl,
//pos1, //pos2, //set, //undo, //replace, //center, //walls
```
this is also rate limited

## 23. custom presets (scoping rules)

outside the actual game, players have their own private "custom preset" world where normal admin restrictions don't apply, but everything is locked to affecting only yourself:

- `player.give`/`teleport`/`launchForward`/`shootProjectile` only work if the target is **you**.
- `world.spawnEntity`/`setBlock`/`fillBlocks`/`playSound` only work inside **your own** preset
- mutating `entity` methods only work on entities in **your own** preset
- `Katton.players.all()` etc only ever return **you**
- item tags set in your preset stay private to your preset
- `Katton.makeAdminExecuteCommand` does basically nothing in a preset

## 24. limits - may be a tiny bit different

| limit | default |
|---|---|
| max scripts per player | 3 |
| max script source size | 256 KB |
| max loop iterations per script run | 1,000 |
| max operations per script run | 50,000 |
| max function call depth | 64 |
| max function calls per script run | 5,000 |
| max string length | 32,768 chars |
| max list/map size | 10,000 entries |
| max `Katton.vars` keys per bucket | 100 |
| max scheduled tasks per owner | 250 |
| world entity cap | 100 total in world |
| `fillBlocks` max volume per call | 4,096 blocks |
| world mutation rate limit | ... |
| max item stack amount | 64 |
| max launch/projectile speed | 6 |
| admin command rate limit | ... |

write scripts that comfortably stay under these. example: don't loop more than ~1000 times in one function call, don't fill huge regions in one `fillBlocks` call (split into chunks instead), don't generate unique `Katton.vars` key names in a loop

## 25. common errors (so you can avoid triggering them)

- `function parameters cannot have types`: never write `function f(a: Type)`
- `invalid permission '...'`: permission must be exactly `"admin"`, `"creative"`, or `"all"`
- `duplicate command name`: command names must be unique per script (and across your scripts)
- `unknown event "..."`: must match section 21 exactly
- `division by zero`: guard against zero divisors
- `undefined variable`: don't use a variable before declaring it / check spelling
- `cannot reassign 'val ...'`: use `var` if it needs to change
- `list index N out of bounds`: check `.size()` before indexing
- `missing required argument`: builtin calls have required params, check signatures above

## 26. full worked example

```csharp
// a wand that launches you forward on right click, with a 3 second cooldown per player
var onCooldown = {} // map of player uuid -> true while on cooldown

@Katton.command(name = "leapwand", permission = "all")
function giveLeapWand(sender, args) {
    val wand = Katton.item("stick")
    wand.setName("&aLeap Wand")
    wand.setTag("ability", "leap_wand")
    sender.give(wand)
}

@Katton.listen("player_rightclick")
function onLeap(event) {
    val item = event.item
    if (item == null || item.getTag("ability") != "leap_wand") {
        return
    }

    val uuid = event.player.uuid
    if (onCooldown.containsKey(uuid)) {
        event.player.sendMessage("&cstill on cooldown!")
        event.cancel()
        return
    }

    event.player.launchForward(horizontal = 1.8, vertical = 0.65)
    event.player.sendMessage("whoosh")
    event.cancel()

    onCooldown.set(uuid, true)
    Katton.after(3.seconds) {
        onCooldown.remove(uuid)
    }
}
```

```csharp
// a self cancelling countdown that shows a title to everyone, then starts the game
var countdown = 5
var countdownTaskId = 0

@Katton.command(name = "startgame", permission = "admin")
function startGame(sender, args) {
    countdown = 5
    countdownTaskId = Katton.every(1.seconds) {
        if (countdown > 0) {
            for (p in Katton.players.all()) {
                p.sendTitle("&e" + countdown, "")
            }
            countdown = countdown - 1
        } else {
            for (p in Katton.players.all()) {
                p.sendTitle("&aGO!", "")
            }
            Katton.cancel(countdownTaskId)
        }
    }
}
```

---

### checklist before returning any Katton script

1. every `@Katton.command` function takes exactly `(sender, args)`; every `@Katton.listen` function takes exactly `(event)`
2. `permission` is `"admin"`, `"creative"`, or `"all"`: nothing else
3. event names come only from section 21
4. no `while` loop anywhere: use `for (i in a..b)`/`downTo`/recursion
5. no type annotations on function parameters
6. null checked anything that can be null (`event.item`, `event.block`, `.get(...)` results, `Katton.pick(...)`)
7. loops/operations stay comfortably under the limits in section 24
8. if storing a task id for later cancellation, it's a top level `var`, not a local `val`
