clay

Language tour

A walk through Clay’s syntax and object model. Everything here runs in the VM (clay file.clay) and natively (clay --compile file.clay). The built-in prototypes are covered in Core objects.

Everything is an object

Integers, strings, booleans, arrays, blocks — all objects. All operations are message sends.

42 println              // send 'println' to an integer
"hello" length          // send 'length' to a string

Variables

A variable comes into existence when it’s first assigned: count = 0. One assigned at the top level of a program is global — visible everywhere, including in code written above the assignment. One assigned inside a block belongs to that block, unless the block is written at the top level of a file that has a top-level variable of that name: then the block assigns that one ([1, 2, 3] each { |n| total = total + n } adds to the file’s total).

Reading a variable that is never defined is an error, reported before the program runs (in the VM and with --compile alike), so a typo can’t silently become nil:

```clay norun p = Pointt clone // error: undefined variable ‘Pointt’


Inside a method a bare name can also be one of `self`'s slots (see
[Implicit self](#implicit-self-in-methods)), so names there aren't checked.

## Message passing

Messages use IO-style syntax: `receiver message(args)`. Parentheses are optional for zero-argument messages.

```clay
arr = [10, 20, 30]
"hello" println          // no parens (preferred for unary)
"hello" println()        // parens also work
"hello" length           // returns 5
arr at(0)                // message with one arg: 10
arr each { |x| x println }  // message with trailing block

Binary operators

Binary operators (+, -, *, /, %, ==, !=, <, >, <=, >=, and the bitwise operators) are messages sent to the left operand.

3 + 4         // sends '+' to 3 with arg 4
10 > 5        // sends '>' to 10, returns true

Standard math precedence applies.

Messages bind tighter than operators. x size + 1 is (x size) + 1, which is usually what you want — but it also means a message after an operator goes to the operand next to it, not to the whole comparison:

x = 5
(x == 5) ifTrue { "five" println }   // parenthesize the condition
// x == 5 ifTrue { ... } would send ifTrue to 5, not to the comparison:
// "integer does not understand 'ifTrue' (a message binds tighter ...)"

The same goes for loops: { i < 3 } whileTrue { ... } puts the condition in a block, which is what whileTrue is sent to. The unary operators follow the rule too: -p length is -(p length) and !list includes(x) is !(list includes(x)).

Operator overloading

Custom types can define operator methods. Define them inside clone bodies or use setMethod:

Vec = Object clone {
  x = 0
  y = 0
  init(vx, vy) { self x = vx; self y = vy }

  +(other) { Vec new(x + other x, y + other y) }
  ==(other) { x == other x && y == other y }

  toString() { "Vec(" + x toString + ", " + y toString + ")" }
}

v1 = Vec new(1, 2) + Vec new(3, 4)   // Vec(4, 6)
v1 == Vec new(4, 6)                   // true

// Or use setMethod for external definition
Vec setMethod("*", { |scalar| Vec new(self x * scalar, self y * scalar) })
Vec new(2, 3) * 5   // Vec(10, 15)

Overloadable operators: the binary +, -, *, /, %, ==, !=, <, >, <=, >=, &, |, ^, <<, >> (each a method with one parameter, named like the operator), and the unary -x (sends negated), !x (sends not) and ~x (sends bitNot), methods without parameters. For built-in numbers, the fast integer/float path is used automatically; the custom method is only called for non-numeric types.

Money = Object clone {
  cents = 0
  init(c) { cents = c }
  +(other) { Money new(cents + other cents) }
  *(n) { Money new(cents * n) }
  negated() { Money new(0 - cents) }
  ==(other) { (other hasSlot("cents")) && cents == other cents }
  toString() { "${cents}c" }
}

m = Money new(150)
m += Money new(50)     // uses +
m *= 2                 // uses *
m println              // 400c
(-m) println           // -400c: sends negated
(m != Money new(400)) println   // false: != uses ==
(m != nil) println     // true

Prototypes and cloning

Objects are created by cloning a prototype and defining slots (data) and methods:

Point = Object clone {
  x = 0
  y = 0

  moveTo(newX, newY) {
    x = newX
    y = newY
  }

  toString() {
    "(" + x toString + ", " + y toString + ")"
  }
}

p = Point clone
p moveTo(3, 4)
p toString println   // (3, 4)

Either brace style works: the { of a clone body or a method body may also start the next line.

Counter = Object clone
{
  count = 0

  increment()
  {
    count = count + 1
  }
}
Counter increment
Counter count println   // 1

For a clone body on the next line, the { must be alone on its line. A { with more after it on the line starts the next statement instead, as a block:

Shape = Object clone
{
    sides = 0
}
n = 0
s = Shape clone
{ n < 3 } whileTrue { n = n + 1 }   // a loop, not the clone's body
n println                            // 3

Inside methods, bare identifiers like x resolve to slots on self — both for reads and writes: if self has a slot x, then x = val writes to it (Io-style updateSlot semantics). Names that aren’t slots create method-local variables. Use self x = val when a parameter shadows a slot name, as in the init pattern below. The exact rules are in Implicit self.

Super

Use super to call the parent prototype’s version of a method:

Animal = Object clone {
    speak() { "..." }
}

Dog = Animal clone {
    speak() { super speak + " Woof!" }
}

Dog speak println   // ... Woof!

Super works correctly through multi-level chains:

A = Object clone { greet() { "A" } }
B = A clone { greet() { super greet + "B" } }
C = B clone { greet() { super greet + "C" } }
C greet println   // ABC

super dispatches from the prototype where the method was defined, not from self, so it is safe with deeply cloned instances.

Slot access

Read a slot by sending its name as a zero-argument message, and write it with assignment syntax on the receiver:

Point = Object clone {
  x = 0
  y = 0
}
p = Point clone
p x println     // 0 (reads the 'x' slot, inherited from Point)
p x = 42        // sets slot 'x' on p
p x println     // 42
Point x println // 0 — writes are always local to the receiver

Slot reads walk the prototype chain — if the object doesn’t have the slot, its parent is checked, and so on.

Slots and methods share one namespace, and the nearest definition along the chain wins: a slot hides a method of the same name inherited from further up (on the same object, a method wins over a slot). So a slot may be named like one of Object’s methods:

Node = Object clone {
  parent = nil      // hides Object's `parent` method for nodes
  type = "node"     // hides Object's `type`
}
n = Node clone
n parent println    // nil
n type println      // node
(Object clone parent == Object) println   // true — the method, elsewhere

Implicit self in methods

Inside a method body, bare identifiers that aren’t local variables automatically resolve to self slots. This means you can write:

Point = Object clone {
  x = 0
  y = 0
  toString() { "(" + x toString + ", " + y toString + ")" }
}

The lookup order is: local variable or parameter → captured variable → a slot or method declared in the enclosing clone body → top-level variable (wherever it is assigned in the file) → self slot or method. So a slot declared in the object’s own body always beats a top-level variable of the same name, which keeps a brick’s objects working whatever names the script using them chooses:

Config = Object clone {
  path = "/etc/app.conf"
  show() { path }          // the slot, not the top-level `path` below
}
path = "./local.conf"
Config show println        // /etc/app.conf

Calls with arguments resolve the same way, so a method calls another method of self without writing self. name(args) runs a block when name is a variable, and sends self name(args) when it’s a slot or method:

Greeter = Object clone {
  greeting = "Hello"
  format(name) { "${greeting}, ${name}!" }
  greet(name) { format(name) println }   // same as: self format(name)
  greetAll(names) { names each { |n| greet(n) } }
}
Greeter greetAll(["Ada", "Alan"])        // Hello, Ada!  Hello, Alan!

A slot or method that’s only inherited from a prototype, not declared in this clone body, isn’t known when the method is compiled, so there a top-level variable of the same name still wins — write self path to be explicit. Slot writes also resolve implicitly (Io-style updateSlot semantics): x = val in a method writes the slot x if the name is declared in the enclosing clone block or if self (or its prototype chain) already has a slot x when the method is called — for example one created by a constructor. Otherwise x is a new local variable. Assignment in a method, or in a block inside one, never changes a top-level variable (a top-level block does assign the top-level variables of its own file):

Point = Object clone {
  x = 0
  y = 0
  moveTo(nx, ny) {
    x = nx       // writes to slot — no self needed
    y = ny       // same here
  }
}

Counter = Object clone {
  new() {
    c = self clone
    c count = 0     // slot created at runtime, not declared in the clone block
    c
  }
  bump() {
    count = count + 1   // still a slot write: this Counter has a `count` slot
    tmp = 1             // no `tmp` slot, so this is a local
    self
  }
}

c = Counter new
c bump bump
c count println       // 2

The choice is made once per call, when the method (or a block inside it) starts.

Use explicit self when a parameter name shadows a slot name:

Point = Object clone {
  x = 0
  y = 0
  init(x, y) {
    self x = x   // self needed because parameter 'x' shadows slot 'x'
    self y = y
  }
}
(Point new(3, 4) x) println   // 3

Dynamic Methods

Methods can be added to objects after cloning by assigning a block to a slot. The block is automatically invoked when the slot is accessed via message passing (Io-style):

Dog = Object clone {
  name = "Rex"
}

Dog speak = { self name + " says Woof!" }
Dog speak println     // Rex says Woof!

// With arguments
Dog greet = { |other| self name + " greets " + other }
Dog greet("Buddy") println  // Rex greets Buddy

// Methods added this way inherit through the prototype chain
puppy = Dog clone
puppy name = "Buddy"
puppy speak println   // Buddy says Woof!

Note: blocks assigned to slots must use explicit self to access other slots, since the compiler doesn’t know the block will be used as a method.

A block invoked as a method like this has the receiver as self. Any other block keeps the self of the method that made it, wherever it runs: a block a method hands to another object, which calls it back later, still talks to the method’s object (and a block made at top level has no self).

Use getSlot("name") to retrieve the raw block without invoking it:

Dog = Object clone { name = "Rex" }
Dog speak = { self name + " says Woof!" }

block = Dog getSlot("speak")   // the block itself, not its result
(block type) println           // Block

Constructors

Define an init method on a prototype, then create instances with new:

Point = Object clone {
  x = 0
  y = 0
  init(x, y) {
    self x = x
    self y = y
  }
}

p = Point new(3, 4)
p x             // => 3
p y             // => 4

Default parameters

Methods can have default values for trailing parameters:

Greeter = Object clone {
  greet(name, greeting = "Hello") {
    "${greeting}, ${name}!" println
  }
}
Greeter greet("world")             // Hello, world!
Greeter greet("world", "Hi")       // Hi, world!

new clones the prototype and calls init(args...) on the clone if an init method exists. If there is no init, new just clones:

Cat = Object clone { name = "kitty" }
c = Cat new     // clones Cat, no init called
c name          // => "kitty"

Blocks

Blocks are closures. Parameters go between pipes:

doubler = { |x| x * 2 }
doubler(5) println         // 10
doubler value(5) println   // 10: the same call, written as a message

// No-arg block
greet = { "hello" println }
greet()

doubler(5) is shorthand for doubler value(5). A bare doubler (no parentheses) is the block itself, so you can store it or pass it on: [1, 2] map(doubler).

Trailing block syntax

When the last argument to a message is a block, you can write it outside the parentheses:

arr = [1, 2, 3]
x = 5
arr each { |x| x println }          // instead of arr each({ |x| x println })
arr map { |x| x * 2 }               // instead of arr map({ |x| x * 2 })
arr reduce(0) { |acc, x| acc + x }  // block follows the parenthesized args
(x > 0) ifTrue { "yes" println }    // control flow uses this too

Control flow

Booleans are objects. Control flow is message passing with blocks:

x = 5
(x > 0) ifTrue { "positive" println }
(x > 0) ifFalse { "non-positive" println }

// Chaining ifTrue/ifFalse — the whole expression has a value
sign = (x > 0) ifTrue { "positive" } ifFalse { "non-positive" }
sign println           // positive
// either order works
((x > 0) ifFalse { "non-positive" } ifTrue { "positive" }) println   // positive

In methods and blocks, ifTrue/ifFalse with a block written right there are compiled in place, so they cost no more than an if would: the block’s code runs without a block being made or a message sent. They still behave exactly like the messages, but that means they only work on true, false and what ifTrue/ifFalse return — an object of your own with an ifTrue method gets a TypeError instead of the message.

Blocks capture variables from their enclosing scope (closures). Captured variables are shared by reference — mutations in one closure are visible to all closures that captured the same variable:

Factory = Object clone {
  multiplier(factor) {
    { |x| x * factor }   // 'factor' is captured from the method scope
  }

  // Shared captures
  makeCounter() {
    n = 0
    inc = { n = n + 1; n }
    dec = { n = n - 1; n }
    [inc, dec]                // both closures share 'n'
  }
}

triple = Factory multiplier(3)
(triple value(5)) println       // 15

pair = Factory makeCounter
inc = pair at(0)
dec = pair at(1)
inc value
inc value
(dec value) println             // 1 — dec sees inc's changes

Return

return exits a method early with a value. Bare return returns nil:

Shapes = Object clone {
  area(w, h) {
    (w <= 0 || h <= 0) ifTrue { return 0 }
    return w * h
    "never reached"
  }
}
(Shapes area(3, 4)) println     // 12
(Shapes area(0 - 1, 4)) println // 0

return inside a block returns from the method the block was written in, however deeply the block is nested, so it can end a loop early (finally blocks still run on the way out):

Finder = Object clone {
  firstOver(items, limit) {
    items each { |x| (x > limit) ifTrue { return x } }
    nil
  }
}
(Finder firstOver([3, 8, 12, 20], 10)) println   // 12
(Finder firstOver([1, 2], 10)) println           // nil

A block that outlives its method can’t return from it any more; calling its return then raises a RuntimeError. Outside methods there is nothing to return from, so return only ends the innermost block it is written in — inside a top-level block, (x > 1) ifTrue { return "big" } ends just the ifTrue block. Put such logic in a method.

Break and continue

break exits the nearest loop. continue skips to the next iteration:

[1, 2, 3, 4, 5] each { |n|
  (n == 3) ifTrue { break }
  n println   // prints 1, 2
}

This works the same with times, whileTrue, whileFalse, and any other message you pass a block literal to, including methods you write yourself. As in Ruby, a break in such a block ends the call it was passed to, and that call gives nil. A continue ends just that run of the block, which gives nil too:

evens = [1, 2, 3, 4, 5] map { |n|
  (n > 4) ifTrue { break }
  n * 2
}
evens println             // nil: the break ended map

halves = [1, 2, 3, 4] map { |n|
  (n % 2 == 1) ifTrue { continue }
  n / 2
}
halves println            // [nil, 1, nil, 2]

That holds however the method runs the block, so break stops an iterator you write, even a recursive one:

Tree = Object clone {
  walk(t, b) {
    t each { |c| (c type == "Array") ifTrue { self walk(c, b) } ifFalse { b value(c) } }
    "walked"
  }
}
Tree walk([1, [2, [3, 4]], 5], { |x|
  (x == 3) ifTrue { break }
  x println               // prints 1, 2
})

The exception is a whileTrue or whileFalse loop: a break there gives the value of the body’s last complete run (see Loops).

As in most languages, a break or continue belongs to the loop it is written in. It can go in a loop’s body or in a block literal passed to a message, including inside the ifTrue/ifFalse and try/catch blocks there. Anywhere else is a compile error, because there is no loop for it to leave:

```clay norun Walker = Object clone { stop() { break } // error: a method body is not a loop } skip = { continue } // error: a block kept for later is not a loop


So a method or a stored block can't stop the caller's loop. Return a value and
let the loop decide:

```clay
done = { |n| n > 2 }
[1, 2, 3, 4] each { |n|
  (done value(n)) ifTrue { break }
  n println   // prints 1, 2
}

A method can also keep a block and run it after the call it was passed to has returned. A break in it then has no call left to end, so it raises a RuntimeError ('break' in a block whose call has already returned).

Imports

Use import to include definitions from another Clay file:

```clay norun import(“math.clay”) // relative to the importing file import(“lib/utils.clay”) // subdirectory paths work too import(“my-brick”) // brick import (see Bricks)


Imports are resolved at parse time. Duplicate imports of the same file are silently skipped. Brick imports (no extension, no path separator) resolve via the `bricks/` directory.

An imported file's top-level variables are globals like the program's own, so every file can read them. Assigning is narrower: a top-level block assigns a top-level variable only when its own file has one of that name. Any other name it assigns is the block's own variable, whatever the other files call theirs:

```clay norun
// lib.clay
calls = 0
sum = { |list|
    total = 0                  // the block's own: lib.clay has no top-level `total`
    list each { |n| total = total + n }
    calls = calls + 1          // lib.clay's top-level `calls`
    total
}

// main.clay
import("lib.clay")
total = 100
sum value([1, 2, 3]) println   // 6
total println                  // 100
calls println                  // 1

So a file’s blocks can’t be broken by the names an importer picks, and can’t change another file’s variables by accident. To change one on purpose, call a block or method of the file that owns it, or keep the value in an object’s slot (Config verbose = true).

Namespaced imports

Add as Name to scope all imported definitions under a namespace object:

```clay norun import(“math.clay”) as Math

Math PI println // access values Math circleArea(2) // call blocks with args Math PI = 2.71828 // mutations are local to the namespace


The imported code executes normally (setting globals), then a namespace object is created with copies of each top-level assignment. The namespace is independent — mutating it does not affect the originals.

## Destructuring assignment

Unpack arrays into multiple variables in a single statement:

```clay
[a, b, c] = [10, 20, 30]
a println   // 10
b println   // 20

// Works with any expression that returns an array
point = [3, 4]
[x, y] = point
"x=${x} y=${y}" println     // x=3 y=4
[first, second] = "a,b,c" split(",")

// Inside blocks and methods too
swap = { |pair| [a, b] = pair; [b, a] }
swap value([1, 2])   // [2, 1]

Extra array elements are ignored when there are fewer targets than elements.

Unary minus

Negative numbers work naturally:

a = 2
b = 3
x = -5
y = -(a + b)
y println          // -5

-x sends negated to x (numbers do it directly), so other types can define it; see Operator overloading.

Like the binary operators, -, ! and ~ bind looser than messages: each applies to the whole message expression after it. A minus right before a number literal is part of the number.

x = -4
(-x abs) println       // -4: -(x abs)
(-5 abs) println       // 5: (-5) abs
(-x abs + 1) println   // -3: unary operators still bind tighter than binary ones

String interpolation

Use ${} inside strings to embed expressions:

name = "Clay"
"Hello, ${name}!" println       // Hello, Clay!
"2 + 3 = ${2 + 3}" println     // 2 + 3 = 5
x = 4
y = 6
"${x} + ${y} = ${x + y}" println  // 4 + 6 = 10

Expressions are automatically converted via toString().

Logical operators

a = true
b = false
(a && b) println     // false — short-circuit AND
(a || b) println     // true  — short-circuit OR
(!a) println         // false — logical NOT (sends 'not')

&& and || short-circuit: the right side is only evaluated if needed. Values are truthy unless they are nil, false, or 0.

Bitwise operators

& (and), | (or), ^ (xor), << (shift left), >> (shift right) and unary ~ (not) work on integers, each with a compound form (&=, |=, ^=, <<=, >>=). They are messages like the other operators, so custom types can overload them; ~x sends bitNot.

(6 & 3) println          // 2
(6 | 3) println          // 7
(6 ^ 3) println          // 5
(~5) println             // -6
(1 << 10) println        // 1024
(-1024 >> 3) println     // -128 — right shift keeps the sign
flags = 0
flags |= 1 << 3          // set bit 3
flags &= ~(1 << 3)       // clear it again
flags println            // 0

Precedence, from loosest to tightest: ??, .., ||, &&, == !=, < > <= >=, |, ^, &, << >>, + -, * / % (the same order as Python). So bit tests need no extra parentheses (flags & 8 == 8 is (flags & 8) == 8, unlike in C), and arithmetic binds tighter than a shift: 1 + 2 << 3 is (1 + 2) << 3.

Operands must be integers (floats raise TypeError). >> is an arithmetic shift, a negative shift count raises RuntimeError, and a << result outside the 62-bit range raises OverflowError like any other integer overflow.

Null-coalescing (??)

Returns the left operand if non-nil, otherwise the right:

x = nil
(x ?? "default") println   // default
a = nil
b = nil
c = 3
(a ?? b ?? c) println      // 3 — first non-nil value

?? has lower precedence than all other binary operators.

Loops

Clay has no loop statements: loops are messages, like everything else. Pick the one that says what the loop does:

To Write
run something n times, counting from 0 n times { \|i\| ... }
count from a to b (both included) (a..b) each { \|i\| ... }
go through a collection items each { \|x\| ... } (or map, filter, reduce)
loop until a condition changes { cond } whileTrue { ... } or whileFalse

n times is the definite loop: when the number of runs is known before the loop starts, use it (or a range’s each) rather than a whileTrue with a counter. There is no counter to set up or forget to step, the count is fixed when the loop starts, and the loop variable belongs to the loop. It is never slower: the compilers count in place (see below), so on the VM it costs the same as a whileTrue with a counter, and compiled with --compile a loop with a small body runs about twice as fast.

5 times { |i| i println }                 // 0 1 2 3 4

// the same, the long way
i = 0
{ i < 5 } whileTrue { i println; i = i + 1 }

whileTrue is for loops whose end depends on what happens in them, such as reading until there is no more input or iterating until a value converges.

whileTrue and whileFalse

Blocks support whileTrue and whileFalse for looping:

i = 0
{ i < 10 } whileTrue {
  i println
  i = i + 1
}

The loop’s value is the value of the body’s last complete run (nil if it never ran), also when a break ends it.

In methods and blocks, a loop whose two blocks are written right there is compiled in place, like ifTrue: no blocks are made and no messages sent, and its break and continue are plain jumps. It behaves exactly like the message. A loop with a break or continue inside another block, such as a try block, is sent as a message instead.

Counting loops

n times { |i| ... } runs its block with i from 0 to n - 1, and (a..b) each { |i| ... } with i from a to b:

total = 0
4 times { |i| total = total + i }
(1..3) each { |i| total = total + i }
total println   // 12

These are compiled in place too, inside methods and blocks: the loop counts in a local of its own, and when the body only reads i (doesn’t assign it or keep it in a block), i is that counter. They still behave like the messages. times gives the body’s last value, and each gives the range. A range’s bounds must be integers. A float count for times is truncated (3.7 times runs 3 times). Because the block runs in place rather than being sent, times with a block literal needs a number, so an object with its own times method can’t take one there.

Arrays

arr = [1, 2, 3]
arr at(0)                     // 1
arr append(4)
arr size                      // 4
arr first                     // 1
arr last                      // 3
arr each { |item| item println }

// Functional methods (trailing block syntax)
arr map { |x| x * 2 }            // [2, 4, 6]
arr filter { |x| x > 1 }         // [2, 3]
arr reduce(0) { |acc, x| acc + x }  // 6
arr find { |x| x > 2 }           // 3

// Utility methods
arr reverse                   // [3, 2, 1]
arr sort                      // [1, 2, 3]: a new array; numbers by value, strings
                              // byte by byte, numbers before strings
arr join(", ")                // "1, 2, 3"
arr contains(2)               // true
arr indexOf(2)                // 1
arr removeAt(0)               // removes first element
arr flatten                   // flattens nested arrays
arr sum                       // sum of numeric elements
arr min                       // minimum value
arr max                       // maximum value
arr avg                       // average value
arr unique                    // unique elements
arr pop                       // remove + return last
arr shift                     // remove + return first
arr slice(1, 3)               // sub-array [index 1..3)
arr + [7, 8]                  // new array with the elements of both (also `concat`)
arr insert(1, "x")            // insert at index
arr setAt(0, "y")             // set element at index

// Equality (element-wise comparison)
[1, 2, 3] == [1, 2, 3]       // true
[1, 2] != [1, 3]             // true

Numbers

Integers and floats are stored directly in the value (no allocation). Mixed operations promote to float.

42                            // integer
0xFF                          // 255 (hexadecimal)
0b1010                        // 10 (binary)
'a'                           // 97 (character literal: the code point)
3.14                          // float
10 / 3                        // 3 (integer division)
10 toFloat / 3                // 3.3333333 (float division)
3.14 + 2                      // 5.1400003 (mixed → float; 32-bit rounding shows)
3.14 toInt                    // 3 (truncation)
(-5) abs                      // 5
5 times { |i| i println }  // prints 0..4

A character literal is a single character in single quotes and is just an integer: its Unicode code point ('a' is 97, '€' is 8364). It accepts the escapes '\n', '\t', '\r', '\0', '\\', '\'', '\"' and '\xHH'. Hex and binary literals use the 0x / 0b prefixes (upper or lower case); like decimal literals they must fit in 62 bits.

Block parameter lists use |a, b|; a block that takes none may be written { || ... } (or simply { ... }).

Strings

Strings support C-style escape sequences: \n (newline), \t (tab), \r (carriage return), \\ (backslash), \" (quote), \xHH (hex byte).

s = "hello world"
s length                            // 11
s at(0)                             // "h"
s contains("world")                 // true
s slice(0, 5)                       // "hello"
s split(" ")                        // ["hello", "world"]
s replace("world", "Clay")          // "hello Clay"
try { s toInt } catch { |e| e type() }   // TypeError — not a number
"42" toInt                          // 42
"3.14" toFloat                      // 3.14
"  hello  " trim                    // "hello"
"hello" upper                       // "HELLO"
"HELLO" lower                       // "hello"
"hello" startsWith("he")            // true
"hello" endsWith("lo")              // true
"hello" reverse                     // "olleh"
"hello" indexOf("ll")               // 2
"abcabc" lastIndexOf("bc")          // 4
"ab" repeat(3)                      // "ababab"
"42" padLeft(5, "0")                // "00042"
"hi" padRight(8)                    // "hi      "
"apple" < "banana"                  // true: byte by byte, as sort orders strings
"Zebra" < "apple"                   // true: upper case bytes come first
"app" < "apple"                     // true: a prefix comes first
"line1\nline2" println              // prints two lines
"col1\tcol2" println                // tab-separated

Comments

// line comment
/* block comment */

Dict (HashMap)

A Dict keeps its entries in the order their keys were first added: keys, values, each, entries and toString all follow it. Updating a key keeps its place; removing it and adding it again moves it to the end.

Dict literals use #{} syntax — keys are identifiers that become strings:

d = #{name: "Clay", version: 1}
d get("name")              // "Clay"
empty = #{}
nested = #{outer: #{inner: 1}}

The Dict prototype also supports programmatic construction:

d = Dict clone
d set("name", "Clay")
d set("version", 1)

d get("name") println       // "Clay"
d has("name") println       // true
d size println              // 2
d remove("version")

// Iteration
d each { |key, value|
  "${key}: ${value toString}" println
}

// Inspect
d keys println              // [name]
d values println            // [Clay]
d toString println          // {name: Clay}

// Equality (key-value comparison)
d1 = Dict clone; d1 set("a", 1)
d2 = Dict clone; d2 set("a", 1)
d1 == d2                    // true

// Merge, entries, clear
other = #{"version": 2}
d merge(other)              // merge other dict into d (mutates d)
d entries                   // [[key1, val1], [key2, val2], ...]
d clear                     // remove all entries

Error handling

Clay provides try/catch/finally blocks and raise for error handling. Try/catch frames use a dynamic linked list (no fixed depth limit), so deeply nested loops and recursive code work without hitting an artificial ceiling:

// Catch errors — try/catch is an expression
result = try {
  10 / 0
} catch { |e|
  "Caught: " + e message
}
result println             // Caught: division by zero

// Raise custom errors
r = try { raise("something went wrong") } catch { |e| e message }
r println                  // something went wrong

// Errors have message() and type() methods
try {
  nil banana
} catch { |e|
  e type println    // NilError
  e message println // message 'banana' sent to nil
}

// Finally runs whether try succeeds or fails
try {
  File read("no-such-file.txt")
} catch { |e|
  ("Error: " + e message) println
} finally {
  "cleanup always runs" println
}

finally runs on every way out of a try: after the try block succeeds, after catch handles an error, and before an error leaves the try — one with no catch (try { ... } finally { ... } cleans up and lets the error propagate), or one raised by the catch block itself. break, continue and return pass through it the same way. An error raised inside finally replaces the one in flight.

A message an object has no method for raises MethodNotFound, and the message says what the object was: Array does not understand 'byteAt' (the name is what type returns: String, Dict, and so on. A prototype you assign to a top-level variable, as in Dog = Object clone { ... }, is named after the variable, so it and its clones say Dog; an object created anywhere else, such as inside a method, is just an Object. Numbers say integer or float).

Error types include DivisionByZero, OverflowError (integer results outside the 62-bit range), MethodNotFound, NilError, TypeError (an argument of the wrong type, e.g. Math sqrt("x")), ArgumentError (a missing or invalid argument, or too many arguments to a method), and RuntimeError (for user-raised strings).

Methods written in Clay raise ArgumentError when called with more arguments than they declare (fewer is fine — missing parameters are nil or take their defaults). Blocks accept extra arguments, so each { |x| ... } works on a Dict too.

Stack traces

Errors automatically capture a stack trace showing the call chain:

boom = { raise("deep error") }
middle = { boom value }

try {
  middle value
} catch { |e|
  e stackTrace println
  // Output:
  //   at example.clay:1 in block
  //   at example.clay:2 in block
  //   at example.clay:5 in block
  //   at example.clay:4 at top level
}

Each line is a place in the code and what that place is in: a method (in check), a block (in block), or the top level. stackTrace() is every place that was recorded, newest first, and toString() includes it.

An error nothing catches ends the program with a report on stderr: the error and the line it was raised on, then the calls that led to it, newest first (clay, clayc and compiled programs print the same):

app.clay:6: RuntimeError: bad value 2
  at app.clay:6 in check
  at app.clay:5 in step
  at app.clay:4 in run
  at app.clay:8 at top level

The first line is the error’s type and message, and the file and line it was raised on. Then each line is a place in the code, newest first, and the method or block it is in: the error was raised on line 6 in check, which was called on line 5 in step (from the block it gives each), which was called on line 4 in run, which the top level called on line 8. In a program of several files, each line names its own file; a file of a brick bundled with Clay is named from its brick (stdlib/test/src/main.clay) instead of by its full path. So that what matters stays visible, the report leaves out a block’s line when the next line is the same place (a block written on the line that runs it), shows a repeated line once with a count ([previous line repeated 62 more times], which is what a runaway recursion looks like), and when it is still longer than about two dozen lines keeps the first twelve (where it went wrong) and the last twelve (where it started) with a “not shown” line between. The shadow stack records the first 64 nested calls; deeper ones are counted in a line at the top. e traceback is this text for an error you caught.

An error raised in a Fiber that nothing in the fiber catches ends the fiber and comes out of resume, where a try can catch it.

Objects can override doesNotUnderstand for proxy-style dispatch:

Proxy = Object clone {
  doesNotUnderstand(name, args) {
    "forwarding: " + name
  }
}
(Proxy anything) println    // forwarding: anything

Reflection

Dog = Object clone { _name = "Dog" }
Poodle = Dog clone {}

Poodle parent == Dog          // true (walk the prototype chain)
Poodle hasSlot("_name")       // true
Poodle hasMethod("clone")     // true (inherited from Object)
Poodle methods              // array of method names
Poodle slots                // array of slot names
Poodle type                 // "Dog" (from _name slot)

← Guide index