Learn Rey, one idea at a time.
A practical language guide with runnable examples. Read a concept, inspect its syntax, then edit and run Rey code without leaving the page.
Each topic follows the same path: a short explanation, the rules to remember, a syntax signature, and an embedded playground. Use Run to execute, Edit Code to experiment, and Reset to restore the example.
Lexical Structure & Syntax
Rey source is made of declarations, expressions, and blocks. A semicolon terminates each statement; the closing brace of a block does not need one.
- End declarations, assignments, returns, and expression statements with a semicolon.
- Use // for a line comment and /* … */ for a block comment. Block comments do not nest.
- Names are case-sensitive. String literals use double quotes and support interpolation with {expression}.
statement := declaration | assignment | expression ;
// line comment
/* block comment */// Semicolons finish statements; braces finish blocks.
var language: string = "Rey";
/* A block comment can span
more than one line. */
println("Hello from " + language + "!");Types & Type System
Rey uses lowercase primitive type names and supports nullable and union types. An annotation documents the value a declaration can hold, while inference can fill in straightforward cases.
- Primitive types: int, float, bool, char, string, and void. void is used as a function return type.
- Append ? to make a type nullable, such as string?; compare a nullable value with null before using it.
- Use A | B to describe a value that can have either type, then narrow it before type-specific work.
var count: int = 3;
var caption: string? = null;
var id: int | string = 42;var caption: string? = null;
if caption == null {
caption = "guest";
}
var id: int | string = 42;
id = "REY-42";
println(caption + " / " + id);Variables & Mutability
Choose the binding keyword to make mutation explicit. A var may be reassigned; a const binding is fixed after its initial value is set.
- Use var for a value that changes over time.
- Use const for a value that should not be reassigned.
- Add a type annotation when it clarifies intent; otherwise Rey can infer a type from the initializer.
var name: Type = value;
const NAME: Type = value;var visits: int = 1;
visits += 1;
const language: string = "Rey";
println(language + " visits: " + visits.toString());Operators & Expressions
Expressions combine values and produce a result. Arithmetic, comparisons, and short-circuit logical operators can be composed using the usual precedence rules.
- Arithmetic includes +, -, *, /, and %. Comparisons include ==, !=, <, <=, >, and >=.
- Use && and || for short-circuit logic. Bitwise operations are available through bitAnd, bitOr, bitXor, bitNot, bitShl, and bitShr.
- Range patterns use a..b. For iteration, range(start, end) starts at start and stops before end.
result := left + right * factor;
condition := ready && count >= 1;
range pattern := start..endvar base: int = 7;
var withinBounds: bool = base > 5 && base < 10;
var shifted: int = bitShl(3, 2);
println((base + 3 * 2).toString());
println(withinBounds.toString());
println(shifted.toString());Control Flow
Use conditionals to choose a path and loops to repeat work. Conditions evaluate to booleans, and loop bodies are blocks enclosed in braces.
- if / else handles branching; parentheses around the condition are optional.
- while repeats while its condition is true. loop repeats until break; continue skips to the next iteration.
- for value in collection visits each item. Numeric ranges can be iterated with range(start, end).
if condition { … } else { … }
while condition { … }
for value in collection { … }var count: int = 0;
while count < 2 {
count += 1;
}
if count == 2 {
println("ready");
}
for value in [1, 2] {
println(value.toString());
}Pattern Matching
match compares a value against ordered patterns and runs the first matching arm. Arms can name enum variants, bind payloads, match supported ranges, or use a wildcard fallback.
- Use Enum::Variant to match a named variant; add a binding such as Enum::Value(item) to capture a payload.
- Integer range patterns use a..b.
- Use _ as the catch-all arm. Include all cases or a wildcard to make the intent clear.
match value {
Enum::Variant => { … },
start..end => { … },
_ => { … }
}enum Direction {
North,
South
}
var direction = Direction::North;
match direction {
Direction::North => { println("head north"); },
Direction::South => { println("head south"); },
_ => { println("unknown direction"); }
}Functions, Lambdas & Closures
Named functions package reusable behavior. Arrow lambdas provide compact function values, and a closure can use values from the surrounding scope.
- Declare a named function with func, typed parameters, and an optional return type annotation.
- Write a lambda as (parameters) => expression. A block body can contain multiple statements.
- A closure can refer to bindings from its surrounding scope; keep captured state simple and explicit.
func name(value: Type): ReturnType { … }
var transform = (value: Type) => expression;func add(a: int, b: int): int {
return a + b;
}
var factor: int = 3;
var triple = (value: int) => value * factor;
println(add(triple(4), 2).toString());Structs & Methods
A struct groups named fields into a custom type. Fields and methods are private by default; mark members pub when they should be available to callers.
- Declare fields inside the struct body and expose public fields with pub.
- Declare methods with pub func methodName(...) when callers outside the module need them.
- Create a value with StructName { field: value } and call methods with dot syntax.
struct Name {
pub field: Type,
pub func method(): Type { … }
}
var item = Name { field: value };struct Rectangle {
pub width: int,
pub height: int,
pub func area(): int {
return self.width * self.height;
}
}
var card = Rectangle { width: 4, height: 5 };
println(card.area().toString());Enums & Algebraic Data Types
Enums describe a value that is one of a fixed set of variants. A variant may be a simple label or carry typed payload data, making enums useful for modeling states and events.
- Declare variants inside enum braces; payload types go in parentheses after the variant name.
- Construct a variant with Enum::Variant(value).
- Use match to inspect a variant and bind its payload.
enum Event {
Click(int),
Message(string),
Closed
}
var event = Event::Click(3);enum Event {
Click(int),
Closed
}
var event = Event::Click(3);
match event {
Event::Click(count) => { println("clicks: " + count.toString()); },
Event::Closed => { println("closed"); },
_ => { println("other event"); }
}Modules, Imports & 'pub' Visibility
Modules organize code and control which declarations other files can use. Import a module or selected names, and mark exported functions and types with pub.
- Use import std::module; for a module namespace, or import std::module::{name} for selected symbols.
- A relative file import can load a project module, for example import "helpers.rey";.
- pub makes a declaration available across module boundaries; unmarked declarations remain private.
import std::math::{sqrt};
pub func greet(name: string): string { … }import std::math::{sqrt};
pub func greet(name: string): string {
return "Hello, " + name;
}
println(greet("Rey"));
println(sqrt(81.0).toString());Collections
Rey provides growable vectors and string-keyed maps, plus Option and Result types for values that may be absent or represent success and failure.
- Use Vec<T> for ordered values and HashMap<string, V> for key/value lookup.
- Option<T> is Some(value) or None. Result<T, E> is Ok(value) or Err(error).
- Check isSome() or isOk() before calling unwrap(); use unwrapOr(fallback) when a default is appropriate.
var items: Vec<int> = Vec.new();
var lookup: HashMap<string, int> = HashMap.new();
var maybe: Option<int> = Option::Some(1);
var result: Result<int, string> = Result::Ok(1);var scores = Vec.new();
scores.push(6);
scores.push(7);
var total = scores.reduce((sum: int, value: int) => sum + value, 0);
var lookup = HashMap.new();
lookup.set("total", total);
var maybeTotal = Option::Some(lookup.get("total"));
var outcome = Result::Ok(maybeTotal.unwrap());
println("sum: " + outcome.unwrap().toString());Standard Library & System Operations
Built-ins cover everyday output, file access, and operating-system tasks. The browser playground uses a virtual filesystem, so file examples are safe to run directly in this page.
- Use print or println for standard output; println appends a newline.
- readFile(path) returns file contents, and writeFile(path, data) creates or replaces a file.
- exec(command) runs a shell command in the native Rey runtime. The browser playground does not launch processes, so exec is shown as a signature and is not called in this example.
println(value);
writeFile(path, data);
var contents: string = readFile(path);
var command: Result<string, string> = exec("pwd");writeFile("hello.txt", "Written in the playground");
var contents = readFile("hello.txt");
println(contents);