ScriptLangCore Language Reference

No results found

Try a different search term.

▼ About ScriptLangCore

Overview An embedded scripting language for .NET 11 with NativeAOT support, written by Gérôme Guillemin

ScriptLangCore is an embedded scripting language for .NET 11, shipped as a NativeAOT executable: one self-contained native binary, with no runtime to install and no dynamic code generation. Source text is parsed into an AST, then the top level and every function are compiled to bytecode and executed by an internal VM, with a fallback to direct AST tree-walking for the constructs the VM does not cover. A program is a .slc file, a line typed at the REPL, or a compiled .slcbc bundle. It is written and maintained by Gérôme Guillemin.

Key Features

  • Types: int, long, double, float, decimal, string, bool, char, byte, short, object, DateTime, DateTimeOffset, TimeSpan, nullable (Type?), arrays (Type[]), list literals ([1, 2, 3]), and the framework's own types by name (List<T>, Dictionary<K, V>, Regex, Uri, and the CLR interfaces)
  • Control flow: if/else, while, for, foreach (and await foreach), do-while, break, continue, return, switch, the match expression, and pattern tests with is
  • Functions: named functions, local functions, lambdas (fun / (args) => expr), closures, pure memoization, yield coroutines, default parameter values, params, ref/out, named arguments, and async/await
  • Classes & Structs: Single inheritance, interfaces (with default bodies, implements, is, casts), records, generics, extension members, constructors, destructors, fields, methods, auto-properties ({ get; set; }, { get; private set; }, { get; init; }), object initializers (new Foo { Prop = val }), access modifiers, super/base, struct operator overloads, script-defined enums
  • Delegates: Action<>, Func<>, Predicate<>, event, multi-cast, as casting
  • Additional features: String interpolation ($"...", raw and interpolated forms), null-coalescing (??), null-conditional (?.), range literals (1..5), list comprehensions ([x for x in ...]), destructuring (var (a,b) = ...), using and await using
  • Error handling: try/catch/finally, throw, and refusals that name the position they happened at
  • Built-in APIs: LINQ (30+ methods), JSON, regex, sqlite (typed queries, bulk insert, CSV import), HTTP client and http.Use server pipelines, TCP and WebSocket, COM and Excel automation, Win32 and a Windows UI toolkit (forms, controls, themes), MCI multimedia, clipboard, scheduler, bitwise operations
  • Module system: import cross-file code loading, namespace, RunScript dynamic evaluation, and bytecode bundles (--compile writes a .slcbc, which runs with or without the source text)
  • AOT compatible: the shipped artifact is one native executable built by NativeAOT, with every function running on the internal bytecode VM and a tree-walker fallback for what it does not cover

Modes

CLI modeScriptLangCore.exe script.slc runs a file and exits
REPL modeScriptLangCore.exe interactive shell with dot commands
REPL + auto-runScriptLangCore.exe --repl script.slc starts REPL, runs .run script.slc, then accepts further commands
MCP modeScriptLangCore.exe --mcp MCP server (stdio or --port). Registers tools via RegisterMcpTool() and resources via RegisterMcpResource(). Supports --repl for combined MCP + REPL. See docs/mcp/howto.html.
Compiled bundleScriptLangCore.exe script.slcbc runs a bundle --compile wrote, which needs no source text beside it
ScriptLangCore is written and maintained by Gérôme Guillemin. This reference documents the language as the shipped engine implements it: every entry's rules, refusals and examples are the engine's own behaviour, so what you read here is what a script gets.
Use the search bar above or browse the categories below to find documentation for any keyword, function, or command. Press Ctrl+C at any time in the REPL to interrupt a running script and return to the >>> prompt.

▼ Command line

Command line What the executable runs, and every flag it takes

One argument is a file to run, and its extension decides how: a .slc is parsed and interpreted, a .slcbc is a compiled bundle loaded and run. With no argument the executable starts the REPL. Flags select a different job, and they are listed below in the order you are likely to want them.

--compile <file.slc> [out.slcbc]Builds a bundle from a script and runs nothing, which is how a file that opens a window or never ends can still be compiled. The output goes beside the source unless you name it, and the name is the first argument after the source that is not a flag, so --compile app.slc --source=strip app.slcbc names it too. It also SEALS the bundle: a SHA-256 of the whole file lives in the bundle's own header, so an artifact that changes after it was built is refused by name instead of running, with no companion file to keep in step. It exits 0 when a bundle was written, 2 when the file, the output path or a flag could not be used, and 3 when the file did not parse or the source mode you asked for could not be honoured (the same four numbers a script writes by name as ExitCode.Ok, Usage and Refused). See the Bytecode entry for what a bundle carries, and Keeping a bundle honest for the digest.
<name>.slcbc.sha256 (optional)A SIDECAR, for the stronger two-file check: a SHA-256 in sha256sum's own <hex> <name> shape, which that tool checks too. --compile no longer writes one (the digest travels inside the bundle); a sidecar you place beside a bundle is still honoured by every path load, and a mismatch is refused by name. It is worth having when the expected digest is kept somewhere the artifact itself cannot reach, and Bytecode.WriteBundleManifest(path) writes one for you.
--source=carry|strip|strictWith --compile: which of the engine's three source modes the bundle is written in. carry (the default, and what no flag means) keeps the program text in the bundle; strip leaves it out when that is honest and carries it, saying so in the report, when it is not; strict leaves it out or refuses the compile, naming what could not be carried. A conflicting pair with --no-source, a bare --source, and an unknown spelling are all refused, so the mode is never guessed.
--no-sourceShorthand for --source=strict: leaves the program text out of the bundle, and a body the bytecode cannot reproduce is refused by name instead of being carried, or the bundle would silently differ from its script.
--dump-bytecode <file.slc>Prints the constant table, the locals, the global slots and every compiled function, without running anything. The same compile step as --compile.
--programWith --dump-bytecode: also reports whether the script's TOP LEVEL itself compiled, and if not, which statement declined.
--repl [file.slc]Starts the REPL, and with a file also runs it first (the same as typing .run file.slc at the prompt).
--mcpStarts an MCP server (stdio, or HTTP with --port / --url), and EXECUTES every tool script in the tools directory so they can register themselves with RegisterMcpTool(). --repl combines the server with a prompt. See docs/mcp/howto.html.
--mcp-bcThe same server, but the tools directory holds COMPILED bundles (*.slcbc) instead of sources (*.slc). Each bundle is loaded and run, so its top-level RegisterMcpTool() calls still register: a compiled bundle is not merely a library.
--tools-dir <dir>Where the MCP server looks for tool scripts. Repeatable, and it defaults to tools/ beside the executable. A relative path resolves against the current directory.
--allowed-dir <dir>The directories the MCP server may read and write through its file tools. Repeatable.
--port <n> / --url <url>The HTTP transport's address, instead of stdio.
ScriptLangCore.exe app.slc // run a script ScriptLangCore.exe app.slcbc // run a compiled bundle ScriptLangCore.exe --compile app.slc // write app.slcbc, run nothing ScriptLangCore.exe --compile app.slc app.slcbc // ...where you say ScriptLangCore.exe --dump-bytecode app.slc // what compiled, without running it ScriptLangCore.exe --repl // interactive prompt ScriptLangCore.exe --mcp --port 8765 // MCP server over HTTP ScriptLangCore.exe --mcp-bc --tools-dir ./bundles // ...with compiled tools
A flag is not a script: only the argument naming a file is run, and a file whose extension this build does not know is refused rather than run.
SLC_* environment flags The engine's run-configuration gates: every variable, what it defaults to, and the one rule for reading them, plus the four that belong to the launcher and to a host

These variables configure a RUN, and the engine keeps them in one registry, so the first table below is the whole of them: a gate cannot exist without appearing here, and the SLC_ spelling is derived from the name, so the two cannot drift. They are set in the environment before the process starts, and each is only the starting value: a script can flip the same state later with Diagnostics.Trace(name, ...) or with one of the VmSet* members, and Diagnostics.Traces() reports what the process is currently using. Four more names carry the same SLC_ spelling without being gates, and they are the second table.

One rule reads every flag: 1 turns it on, 0 and false turn it off, and any other value leaves the gate at its own default. So a stray value cannot switch a trace on, and the two gates whose default is on are turned off by naming the off spelling (SLC_TOPLEVEL_VM=0, SLC_CARRIED_STATEMENTS=0).

SLC_TOPLEVEL_VMFlag, on by default. Whether a script's TOP LEVEL runs on the bytecode VM, statement by statement, or on the tree walker. Off is how you compare the two engines in one process, and the member form is VmSetTopLevelEnabled(false).
SLC_CARRIED_STATEMENTSFlag, on by default. Whether a top-level statement the compiler cannot model is carried into a compiled bundle as its own source text, so a bundle answers like the file it was built from. Off compares the two states, and the member form is VmSetStatementCarrier(false).
SLC_VM_MAXFRAMESValue, not a flag: a positive whole number that sets BOTH call-depth caps, the flat frame cap and the tail-call cap. With nothing set the cap is the platform's own (a fixed figure on the JIT build, memory-derived on the shipped AOT build), and Diagnostics.Trace("VM_MAXFRAMES", 0) restores that default. Naming a number here is also how a script that recurses deeply runs under a runner that would otherwise cut it off.
SLC_VM_TRACEFlag, off. Prints one line per instruction the VM executes: the position, the body, the opcode, the operand-stack height and a short note. This is what names the instruction a bail happened at.
SLC_BAIL_TRACEFlag, off. Prints the source site that raised a VM bail (a shape the VM hands to the tree walker), the first question when a compiled body stops part-way.
SLC_NAMED_TRACEFlag, off. Prints every site that consumes a named-argument marker, with the callee it went to and the parameter names it carried.
SLC_COERCE_TRACEFlag, off. Reports each constructor candidate and whether the argument values fit it, which is how a choice between same-arity overloads is explained. It has no engine field, so it is read from the variable and cannot be flipped per name.
SLC_CORO_TRACEFlag, off. Traces a coroutine's lifecycle: creation, resumption, yield, completion and the status a script reads.
SLC_STACK_TRACEFlag, off. Adds the engine's stack to a reported failure, which is what turns a refusal into a trace a developer can read.
SLC_STACK_MAPFlag, off. Prints the VM's frame map when a body is entered, for reading a trace against the frames it names.
SLC_DISABLE_GUARDSFlag, off. Turns the engine's defensive checks off for a run. It exists for measuring what a guard costs, and a process that sets it can be killed by input the guard would have refused.
SLC_SINGLE_INSTANCEFlag, off. Appends the lock's name to the single-instance refusal. The name is a sanitized full path, which is why it is opt-in and the default message is one short line.
SLC_ASYNC_TRACEFlag, off. Prints one line per await that WAITS on the spot rather than suspending, with its site (await, await foreach, await using, http stream, Task.Wait) and how long it waited. The per-shape counts a suite can assert on are Diagnostics.AsyncParks(site).

The state a flag backs is one value with two doors, so a script that calls VmSetTopLevelEnabled(false) and a process started with SLC_TOPLEVEL_VM=0 are the same state, not two. Diagnostics.LogTraces(true) turns the TRACE gates on together and deliberately leaves the two path switches and the frame cap alone, because those are not traces.

// turn every trace on, from a script or a suite Diagnostics.LogTraces(true); // or one gate, with a boolean that answers what it set Diagnostics.Trace("BAIL_TRACE", true); // read what the process is configured with print(Diagnostics.Traces()); // the cap is a value, so it is set and reported as a number Diagnostics.Trace("VM_MAXFRAMES", 50000);

Four more variables carry the SLC_ spelling and are NOT engine gates, so no registry row backs them and Diagnostics.Trace refuses them by name. The engine reads none of them: they say where the engine and its declarations are, or make the launcher report what it loaded, and they are read by the LAUNCHER and by a HOST (and, for SLC_ENGINE_BINDINGS, by a suite or a sample looking for the folder a host would compile against). Each is documented on the embedding page, and they are listed here because this entry is where the whole of the SLC_ namespace is looked for.

SLC_ENGINE_DLLThe exact FILE the launcher loads, consulted BEFORE a copy beside the exe. The installer deliberately does not set it, because a machine-wide value would hijack every app packaged with its own engine.
SLC_ENGINE_HOMEThe DIRECTORY holding ScriptLangCore.dll, which is what an installed engine declares so a launcher or a host copied elsewhere finds it. It is OBEYED rather than consulted: naming a folder that holds no DLL is a refusal, never a fallback to another copy.
SLC_ENGINE_BINDINGSThe DIRECTORY holding this engine's ABI declarations (the C header, the managed delegates and the ctypes module), which the installer writes as {app}\bindings beside the engine it describes. A HOST compiles against it, so no sample derives that folder from SLC_ENGINE_HOME; the engine itself never reads it.
SLC_LAUNCHER_INFOMakes the LAUNCHER report which engine it loaded. The launcher has its own rule rather than the gate rule above: any value other than 0 or false turns it on, so 1 prints the version line (and the verdict JSON) and nothing set is silent.

▼ Types

int 32-bit signed integer. Default: 0

Use for whole numbers in the range -2,147,483,648 to 2,147,483,647. The L suffix forces long type; use as int if you need the runtime value to be int. Numeric widening: int values match as long / as float / as double checks, and vice versa.

int x = 42; int y = 42 as int;
// Declaration and assignment int count = 100; count = count + 1;
Integer overflow: Arithmetic overflow wraps silently (like C# unchecked). No compile-time or runtime error is raised. Example: var x = int.MaxValue + 1; print(x); prints -2147483648. Use long with the L suffix (2147483648L) if the value exceeds int range.
long 64-bit signed integer. Default: 0

Use for large whole numbers or when mixing with int in arithmetic (result promoted to long). Append L suffix to force long type: 42L.

long x = 1000000; long y = 42L;
long big = 1_000_000_000; big = big * 2;
double 64-bit floating-point number. Default: 0.0

Standard floating-point type for most decimal calculations. Append d suffix for explicit double type (3.14d).

double x = 3.14;
double pi = 3.14159; pi = pi * 2;
Equality and truthiness are tolerant for floating values: ==, !=, match and an if test compare with a tolerance of 1e-6, the same constant in both engines, so 0.1 + 0.2 == 0.3 is true and a value of 1e-7 is falsy. Library methods are NOT: an array's Contains comes from LINQ and keeps the CLR's exact equality, so [0.3].Contains(0.1 + 0.2) is false. The split is deliberate see AGENTS.
string UTF-16 text. Default: null (reference type)

Supports concatenation (+) and indexing via LINQ methods. Immutable.

string s = "hello";
string greeting = "Hello" + " " + "world"; print(greeting);
Escapes: \\ \' \" \0 \a \b \f \n \r \t \v, the fixed-width \uXXXX and \UXXXXXXXX, and \xH..H with one to four hex digits. A code point above 0xFFFF becomes a surrogate pair, and one past 0x10FFFF is refused. A single-quoted string and an interpolated one take the same set, and a raw string takes none of them (see raw string literals).
A single-quoted literal holding ONE character is a char, escapes included: 'a', '\n', '\0', '\'', '\u00e9', '\x41' and '\U00000041' are chars, while '', 'ab' and '\n\n' are strings. \xH..H is GREEDY, so '\x4142' is the single char U+4142 and not two characters. An escape whose code point needs two UTF-16 units ('\U0001F600') is a string, since one unit cannot hold it. typeof reports which one you got, and a char-target declaration (char tab = '\t';) takes the character.
String interpolation is supported via $"..." syntax see the string interpolation entry.
string interpolation Embed expressions inside strings with $"{expr}" syntax

String interpolation allows embedding expressions directly inside string literals using $"..." syntax, where {expr} is replaced with the expression's evaluated value. Supports any expression including method calls and arithmetic.

The forms, and what a brace means in each

FormHolesUse it for
$"..."{expr}, a literal brace as {{ / }}a line of text; escapes are processed
$@"..." or @$"..."as $"..."text spanning lines with no escape processing; a " is doubled ("")
$"""...""", or more $N braces open a hole, N being the number of $; fewer than N are literal texta raw template: the text is verbatim, quotes and backslashes included
The dollar count is C#'s, and it is what a field of braces wants: with $$""" a hole is {{expr}} and every single { is itself, so a CSS rule stays a CSS rule. A RAW form has no doubled-brace literal (C# refuses a run of 2N braces and so does this engine): a literal brace wants MORE dollars. A raw form also skips the first line break right after the opening delimiter, exactly like """ on its own (see raw string literals).
An ALIGNMENT pads a hole, as in C#: $"{n,5}" right-aligns in five columns, $"{n,-5}" left-aligns, and it applies AFTER a format specifier ($"{n,6:D5}" pads the formatted text).
Inside a hole, a TERNARY needs parentheses: $"{(ok ? "yes" : "no")}". The bare form is refused with the fix named, because the : after the expression starts a format specifier, which is exactly how C# reads it (a bare $"{ok ? "yes" : "no"}" does not compile there either). A format specifier still comes after the expression ($"{n:N2}"), and ?? and ?. are not ternaries.
A template is always a string, even one that holds nothing but holes: $"{42}" is "42", not the number so $"{n}".Length works and $"{n}" + 1 concatenates instead of adding. Each hole goes through the same display rule as print and +.
var name = "world"; var msg = $"Hello {name}"; // "Hello world"
// Variables and expressions var x = 42; print($"x = {x}"); // "x = 42" print($"2+2 = {2+2}"); // "2+2 = 4" // Method calls var s = "Hello"; print($"upper = {s.ToUpper()}"); // "upper = HELLO" // Escaped braces with {{ }} print($"{{literal brace}}"); // "{literal brace}" // Format specifiers (C#-style) var n = 123; print($"{n:D4}"); // "0123" (zero-padded 4 digits) print($"{n:X}"); // "7B" (hex uppercase) print($"{n:N2}"); // "123.00" (2 decimal places)

Format specifiers reference

Format specifiers follow the {expr:format} syntax. They are mapped directly to (expr).ToString("format") at runtime, so all .NET numeric, date/time, and custom format strings are supported.

SpecifierNameExample (n=123, d=now)
DDecimal (zero-padded integer)$"{n:D4}" → "0123"
XHexadecimal (uppercase)$"{(int)255:X}" → "FF"
xHexadecimal (lowercase)$"{(int)255:x}" → "ff"
NNumber (group separators)$"{(int)1234567:N0}" → "1,234,567"
FFixed-point$"{3.1415:F2}" → "3.14"
CCurrency"${(int)42:C}" → "$42.00" (locale-dependent)
PPercent (×100 + %)$"{(double)0.5:P0}" → "50%"
EScientific notation$"{(double)12345:E2}" → "1.23E+004"
GGeneral (compact)$"{123:G}" → "123"
0Zero placeholder (custom)$"{(int)42:0000}" → "0042"
#Digit placeholder (custom)$"{(int)42:####}" → "42"
dShort date$"{now:d}" → "6/11/2026"
D (Date)Long date$"{now:D}" → "Thursday, June 11, 2026"
tShort time$"{now:t}" → "6:30 PM"
TLong time$"{now:T}" → "6:30:00 PM"
yyyy-MM-ddCustom date format$"{now:yyyy-MM-dd}" → "2026-06-11"
HH:mm:ssCustom time format$"{now:HH:mm:ss}" → "18:30:00"
Internally, $"..." is transformed into string.Concat() calls at parse time. The \{ escape sequence produces a literal {. Format specifiers ({expr:format}) are transformed into (expr).ToString("format") calls.
Verbatim interpolation: Use $@"..." or @$"..." for multi-line interpolated strings where \ is treated literally and "" is the escape for a quote character. Example: $@"Hello {name} on two lines with ""quotes""."
bool Boolean (true/false). Default: false

Used in conditions, logical operators, and if/while/for statements.

A number is not a bool, and casting one is an error: (bool)0 does not compile (C# refuses it too), so write the test instead (0 != 0) or the constant (false / true). Converting a bool to a number is allowed ((int)true is 1), and a text that spells a boolean converts from its text ((bool)"true").

bool b = true;
bool isReady = true; if (isReady) { print("ready"); }
char Single UTF-16 character. Default: '\0'

Enclosed in single quotes.

char c = 'A';
char letter = 'Z'; print(letter); // Result: Z
byte 8-bit unsigned integer (0–255). Default: 0

Use for small positive integers or raw byte data.

byte b = 255;
byte b = 200; print(b + 55); // Result: 255
short 16-bit signed integer. Default: 0

Smaller range than int, useful for memory-constrained scenarios.

short s = 100;
short s = 100; print(s * 3); // Result: 300
float 32-bit floating-point. Default: 0.0f

32-bit floating-point. Less precision than double, use for memory-sensitive applications. Append f suffix to force float type: 42f.

float f = 1.5; float g = 42f;
float f = 2.5; print(f * 2); // Result: 5
Equality and truthiness are tolerant for floating values: ==, !=, match and an if test compare with a tolerance of 1e-6, the same constant in both engines, so 0.1 + 0.2 == 0.3 is true and a value of 1e-7 is falsy. Library methods are NOT: an array's Contains comes from LINQ and keeps the CLR's exact equality, so [0.3].Contains(0.1 + 0.2) is false. The split is deliberate see AGENTS.
decimal 128-bit high-precision decimal. Default: 0.0m

Use for financial/monetary calculations where exact decimal representation matters. Append m suffix to force decimal type: 3.14m.

decimal m = 99.95; decimal n = 3.14m;
decimal price = 19.99; print(price * 3); // Result: 59.97
Arithmetic stays decimal. A decimal PAIR computes in decimal in both engines, so 0.1m + 0.2m is exactly 0.3 and typeof(1.5m + 0m) is "decimal", the exactness the text above promises. A MIXED pair (a decimal with a double or an int) still widens through double, which is the lenient reading of what C# refuses to compile outright. crash_numeric_types.slc pins both.
object Base type for all values. Default: null

Use for untyped variables or heterogeneous collections.

object o = "anything";
object val = 42; print(typeof(val)); // Result: "long" val = "hello"; print(typeof(val)); // Result: "string"
DateTime Date and time value type

Available as a built-in .NET type with .Now, .Ticks, etc.

var now = DateTime.Now;
var start = DateTime.Now; sleep(100); var elapsed = (DateTime.Now.Ticks - start.Ticks) / 10000; print("Elapsed ms: " + elapsed);

A DateTime is not a number: arithmetic and a cast on one are refused, and the sentence names the three ways to get a number out of it. .ToOADate() is the serial a spreadsheet counts in (days since 1899-12-30, so 46024.25 is an afternoon) with DateTime.FromOADate to come back, .Ticks is the tick count since year 1, and .ToString(...) is for display.

var at = new DateTime(2026, 1, 2, 6, 7, 0); print(at.ToOADate()); // 46024.25486111111 print(DateTime.FromOADate(46024)); // 01/02/2026 00:00:00 var serial = 1.0 * at.ToOADate(); // 1.0 * at would be refused, and say why

A cell read through COM arrives as a real DateTime, not as a serial: Excel stores VT_DATE and the bridge converts it, so a date column needs .ToOADate() before it can be multiplied while .ToString("s") or a format string is what to print.

void The return type of a body that answers no value

void declares that a body answers nothing: a free function, a class or struct method, and an event handler all take it. Calling one as a STATEMENT is the ordinary use, and a void body leaves with a bare return;; a return that carries a value from it is refused. It is also what a void handler means to the engine, which calls it and ignores what it answered: an http.MapGet handler that writes ctx itself, a button's Click, a middleware that only logs.

void Log(string s) { print(s); } Log("hello"); class Counter { public int N; public void Bump() { N = N + 1; } } var c = new Counter(); c.Bump(); c.Bump(); print(c.N); // 2
nullable (?) Nullable value types using ? suffix

Value types can be made nullable by appending ? allows null assignment.

int? x = null;
int? count = null; count = 42; double? pi = 3.14;
array ([]) Fixed-size collection of elements of the same type

Created with new type[size], new type[] { values }, the array literal shorthand [1, 2, 3], or accessed via index. All three forms produce a native T[].

var arr = new int[3]; var init = new int[] { 1, 2, 3 }; var li = [1, 2, 3]; // also int[] (shorthand)
var a = new int[3]; a[0] = 10; print(a[0]); // Result: 10

Members

Count / LengthHow many elements the array holds.
IndexOf(value)The position of a value, or -1 when it is not there.
Clone()A SHALLOW copy: a new array holding the same elements, so writing to the copy leaves the original alone while a contained instance stays shared.
Sort() / Sort(fn)Sorts IN PLACE, by the element type's own order or through a script comparer ((int a, int b) => { return a - b; }, which answers a negative, zero or positive number). A comparison that fails keeps its own message.
IsReadOnlyAlways false: an array's elements can be written.
var a = [3, 1, 2]; print(a.Count); // Result: 3 print(a.IndexOf(1)); // Result: 1 a.Sort(); // in place print(a); // Result: [1, 2, 3] a.Sort(fun(int x, int y) { return y - x; }); // a comparer, descending print(a); // Result: [3, 2, 1] var b = a.Clone(); // a new array with the same elements
sbyte 8-bit signed integer (-128 to 127)

Signed byte type. .NET System.SByte. Useful for compact integer storage. Use (sbyte)value to cast.

var b: sbyte = -100;
sbyte min = sbyte.MinValue; // -128 sbyte max = sbyte.MaxValue; // 127
ushort 16-bit unsigned integer (0 to 65535)

Unsigned 16-bit integer. .NET System.UInt16. Useful for Win32 API parameters. Use (ushort)value to cast.

var u: ushort = 65535;
ushort val = (ushort)500;
uint 32-bit unsigned integer (0 to 4294967295)

Unsigned 32-bit integer. .NET System.UInt32. Common in Win32 for handles, flags, and DWORD values. Use (uint)value to cast.

var u: uint = 0xFFFFFFFF; var v = (uint)4000000000;
uint flag = 0x80000000; // Win32 style bitmask print(flag); // 2147483648
ulong 64-bit unsigned integer (0 to 18,446,744,073,709,551,615)

Unsigned 64-bit integer. .NET System.UInt64. Large bitmasks and unsigned arithmetic. Use (ulong)value to cast.

var u: ulong = 12345678901234567890; var v = (ulong)100000000000;
ulong ptr = 0x7FFE00010000; // memory address style
DateTimeOffset Date/time with explicit timezone offset

Represents a point in time relative to UTC with a timezone offset. Unlike DateTime, it unambiguously identifies a single point in time.

var dto = new DateTimeOffset(DateTime.Now, TimeSpan.FromHours(2));
DateTimeOffset now = DateTimeOffset.Now; print(now.Offset); // +02:00:00 print(now.UtcDateTime); // UTC DateTime
TimeSpan Represents a time interval (duration)

Represents an elapsed duration of time. Can be created from hours, minutes, seconds, or milliseconds.

var ts = TimeSpan.FromMinutes(5);
TimeSpan ts = TimeSpan.FromMilliseconds(1500); print(ts.TotalSeconds); // 1.5 var sum = TimeSpan.FromMinutes(3) + TimeSpan.FromSeconds(30);
Result Return value of RunScript() carries execution outcome

Returned by RunScript(). Contains error info, return value, and exit code. Serializable via Json.Serialize().

PropertyTypeDescription
.HasErrorboolTrue if the script encountered an error
.ErrorMessagestring?Error message string
.ErrorInfoErrorInfo?Structured error (code + message)
.ReturnValueobject?The script's return value
.As<T>()T?Typed access coerces the return value through the engine (CoerceTo, so int→long/double/string work); on a mismatch returns default(T) (0/false for value types, null for reference types use a nullable T like int? to observe null); never throws
.Return<T>()TStrict typed access coerces like As, or throws ScriptException (TypeMismatch pattern used by native methods)
.ExitCodeintProcess exit code
.AbortedboolTrue when the script ended itself with exit() (.ExitCode carries the code it asked for)
.CancelledboolTrue when the run was stopped by the token it was given (HasError is true too, and the message reads Stopped: the run was cancelled). Its own flag rather than a code to compare, so a runner says r.Cancelled instead of knowing ErrorInfo.Code
.StackTracestring?.NET stack trace on error

What the three outcome fields say for each way a run can end (a run stopped by its token is an OUTCOME, not a failure: it reads Cancelled, it keeps no error position, and a harness reports it as CANCEL rather than as an error):

The run....Cancelled.HasError.Aborted.ExitCode
finished normallyfalsefalsefalse0
failed (1 / 0, a refusal, a script throw)falsetruefalse0
ended itself with exit(3)falsefalsetrue3
was stopped by the token it was giventruetruefalse0
var cts = new CancellationTokenSource(); var task = Task.Run(fun () { return RunScript(src, false, false, cts.Token); }); sleep(100); cts.Cancel(); // the run stops at its next statement, loop back-edge or sleep chunk var outcome = task.Result; if (outcome.Cancelled) print("stopped on request");
var r = RunScript("return 42;"); if (r.HasError) print(r.ErrorMessage); else print(r.ReturnValue); // 42 print(Json.Serialize(r)); // {"HasError":false,"ExitCode":0,"ReturnValue":42}
var n = r.As<int>(); // 42 var m = r.As<long>(); // 42 (widened via CoerceTo) var t = r.As<string>(); // "42" (coerced to text) try { var bad = r.Return<bool>(); } catch (var ex) { print(ex.Code); } // TypeMismatch (native error pattern)
Array Base class for all array types int[], string[], etc.

Type annotation for any native array. Accepts all array types (int[], string[], decimal[], etc.) regardless of element type. Useful for function parameters that take array literals [1, 2, 3].

Array arr
// Function accepting any array void printLen(Array items) { print(items.Length); } printLen([1, 2, 3]); // 3 int[] accepted printLen(["a", "b"]); // 2 string[] accepted // printLen(42); // runtime error not an array
Array provides runtime validation: passing a non-array value to an Array-typed parameter throws a runtime error. For fixed-type arrays, use object[], int[], string[] etc.
Function The callable contract type lambdas, named functions, bound methods, combined delegates, natives

Function is the first-class callable contract type. It has no runtime representation of its own typeof of a callable reports "Function" but it is usable with is and as, and as a signature annotation type on parameters and return types. v is Function is True for lambdas (fun and => arrow), named functions, bound methods, combined delegates, and native functions; False for non-callables (int, bool, string, ...). as Function returns the value unchanged when callable, and null otherwise.

As a signature type, Function works in named functions, fun/arrow lambdas, methods, and local functions: a parameter declared Function fn accepts any callable (invoked directly as fn(args) inside the body), and a function declared to return Function may return any callable. Passing a non-callable argument or returning a non-callable value is a typed runtime error (Expected a Function, got X.).

A contract names the VALUE, not an ARRAY of them. Function[] fns = [One, Two]; holds two callables and fns[0]() calls one; the same holds for Iterable[] and RandomAccess[]. Element coercion does not apply here: a contract is a shape test, so every element either satisfies it or does not, and only a value that is not a function is refused.

Two declarations of one function name with DIFFERENT parameter lists are an OVERLOAD SET, and each call resolves by argument count then by type: the exact type beats a widening one (Pick(int) wins for an int argument over Pick(long)), and a tie goes to the first declaration. A ref/out position is part of the signature, so F(ref n) reaches F(ref int) even when the argument's value would also fit F(int) beside it, and a params tail is weighed by its ELEMENT type. Named arguments choose the member their NAMES fit: with Nm(int a, string b) and Nm(string a, int b), Nm(b: 1, a: "s") is the second one. A declaration whose signature MATCHES an existing one does not overload, it REPLACES the earlier body, which is what retyping a line at the prompt does. A call no member accepts is refused naming what the name holds, for example No overload of 'Ar' takes 1 argument(s) that fit: the name holds (int), (int, int)., and a by-reference position is spelled with its keyword, as in (ref int), (string).
// One name, two arities, one set: each call picks its member string Ar(int a) { return "one:" + a; } string Ar(int a, int b) { return "two:" + a + "," + b; } print(Ar(7)); // one:7 print(Ar(3, 4)); // two:3,4 // the name is a value too, and the set travels with it var f = Ar; print(f(9) + " / " + f(9, 9)); // one:9 / two:9,9
// A Function-typed parameter is called directly inside the body int Apply(Function fn, int v) { return fn(v); } print(Apply(fun (int x) { return x + 1; }, 1)); // 2 lambda passed as Function // is Function guard fun lambdas, arrows and named functions are callable var f = fun (int x) => x * 2; print(f is Function); // True var g = (int x) => x * 3; print(g is Function); // True arrow lambda print(42 is Function); // False a scalar is not callable print(f); // func <lambda>(int) -> object its own signature print(typeof(f)); // "Function" typeof names the contract, not the storage class // Function return type a factory returns a lambda Function Make(int n) { return fun (int x) { return x + n; }; } print(Make(5)(10)); // 15 // A non-callable argument is a typed runtime error try { Apply(42, 1); } catch (var ex) { print(ex.Message); } // Expected a Function, got Int32
Printing a callable answers its SIGNATURE; typeof answers the contract. print(fn) reads func Add(int, int) -> int for a named function, func <lambda>(int) -> object for a fun or arrow lambda (a lambda declares no return type, so it reports object), and func print(object...) -> object for a native. A body that returns nothing omits the arrow entirely (func NoRet()), and a script function's params tail prints as its element type (func Variadic(int, int) -> int) while a native's variadic tail keeps the dots. So a value that holds a callable reads as what it does, and typeof stays the one-word answer: "Function".
A callable is a Function; the engine's internal storage name for that type is NOT exposed to scripts. Writing the internal name in a script is a runtime error (unknown or undefined type), so Function is the callable contract.
Built-in type keywords match case-sensitively. Function, Iterable, RandomAccess, Tuple, DateTime, ... are real types a lowercase function is NOT one: function foo() { ... } or x is function reports Type 'function' is unknown or undefined (the legacy pseudo-type was treated as object with a warning; it is now rejected). There is no function declaration keyword: name a function by its return type (string Foo(), void Bar(), int Coro()), and reserve the Function type for parameters and returns that hold a callable a lambda or a function pointer such as Function Make(int n) { return (int x) => { return x + n; }; }.
CLR interfaces The .NET interfaces a script can name and use, and what each one is for

A framework interface is a type name like any other: it can be written in a declaration, as a parameter type, in an is/as test and in a cast, and the engine resolves it against the assemblies the process has loaded. A generic spelling carries its arguments, including a nested one (IEnumerable<KeyValuePair<string, int>>), and one written WITHOUT arguments is refused with the fix in the message, which is C#'s own rule. The behaviour behind each interface works too; the table is what a sweep of them measured, on the development build and on the shipped one.

InterfaceWhat works
IDisposableusing, d.Dispose(), and as a parameter type
IAsyncDisposableawait using and await d.DisposeAsync()
IEnumerable<T> / IEnumerator<T>foreach over a script list and over a CLR collection, a parameter type, is
IAsyncEnumerable<T> / IAsyncEnumerator<T>await foreach, and a hand-driven GetAsyncEnumerator() / MoveNextAsync() / Current
ICollection<T> / IList<T> / IReadOnlyList<T>a parameter type that takes a script list or an array, and Count, IndexOf and indexing on the value
IDictionary<K, V>a parameter type that takes a { } literal, plus Count and key indexing, on a raw CLR dictionary too
IComparable<T> / IComparer<T>CompareTo, both as parameter types, and StringComparer.Ordinal as a comparer
IEquatable<T>is IEquatable<string>, and Equals
ICloneableClone(), on an array as well
IFormattable / IFormatProviderToString(format, provider), and both as parameter types
A name nothing defines is refused, in the type and in a type ARGUMENT. x is IAsyncEnumerable<NoSuchType> is refused with the name in the message rather than answered false, the wording an unknown outer name already gets. A TYPE PARAMETER is resolved in a type position, which is what makes a generic body's own test work: o is IEnumerable<T> answers for the instantiation's binding (true for Gen<string>(new List<string>())), in a return, an if, a &&, a var initializer, a bare is T, a loop body and a lambda alike.
Not covered, and worth knowing before planning around it: IQueryable<T> and Expression<T> cannot be named, because nothing the engine does loads the assemblies they live in. Sorting a VALUE is covered (list.Sort() and list.Sort(comparer), see the List<T> and array entries), and an ORDERED SEQUENCE (OrderBy's result) is covered too: OrderBy(key, comparer) takes a comparer for the KEYS, OrderByDescending answers the same members, and .ToList() / .ToArray() materialize it. What is still refused is Comparer<int>.Default, so a comparer is written as a function ((a, b) => { return b.CompareTo(a); }) where the default order will not do.
Internal Types Registry of script-exposed internal types script-facing names, is/typeof/print alignment, Dispose

ScriptLangCore exposes several internal types to scripts through a central registry. The script-facing name carries no Script prefix and no namespace it is a functional name shared by is / as, typeof, print() and nameof() (via ToString()). Every value also answers a callable Dispose(): real cleanup for resource-owning types, a safe no-op otherwise.

A type name is one the engine registers. The primitive names are lowercase (string, int, long, bool, char, double, float, decimal, byte, sbyte, short, ushort, uint, ulong, object); the CLR-cased spelling is the script name only where the CLR type is the script type (DateTime, DateTimeOffset, TimeSpan). A declaration written String, Int, Long or Object is refused with the spelling to use instead: 'String' is not a name this engine registers for a type: write 'string'. A CLR type the engine has no script name for is unaffected (StringBuilder, Control, List<T>), and a name nothing defines stays the usual unknown-type warning rather than an error.

Script-facing nameprint / typeof / nameofDispose()
TupleTupleno-op
KeyValuePairKeyValuePairno-op
LazyDeserializedListthe declaration the read was asked for (List<int>, string[], IList)no-op
ErrorInfoErrorInfo (print/nameof show Message)no-op
ResultResultno-op
WeakRefWeakRefno-op
MetaMetano-op
MemBufferMemBufferreal frees pointer, drops Mem.LiveBuffers()
DynamicLibraryDynamicLibraryreal frees the loaded library
OrderedEnumerableOrderedEnumerableno-op
FileStreamReaderFileStreamReaderreal closes the reader
FileStreamWriterFileStreamWriterreal closes the writer
MessageInfoMessageInfono-op
CipherInfoCipherInfono-op
CronExpressionCronExpressionno-op
CronType (enum)enum member namen/a (enum)
SqliteIteratorSqliteIteratorreal releases the statement
SqliteMappingIteratorSqliteMappingIteratorreal forwards to the inner iterator
SqliteRowSqliteRowno-op the row owns nothing, the cursor does

Iterable a predicate type

Iterable is a guard, not a value type. It has no runtime representation and never appears in print()/typeof. It is usable with is and as: v is Iterable is True for arrays, lists, tuples, dicts, HashSets, LINQ results, coroutine generators, and strings, and False for scalars (int, bool, double, ...). as Iterable returns the value unchanged when iterable, and null otherwise. typeof still reports the concrete type name (int[], List<int>, Tuple, ...) Iterable is a contract, not a replacement name.

It exists so one guard covers every collection kind foreach and LINQ can enumerate, instead of chaining v is List, v is Array, v is Tuple, v is Dictionary, ... together.

// One guard for heterogeneous collection handling void Process(object v) { if (v is Iterable) { var n = 0; foreach (var e in v) { n = n + 1; } print("iterable, " + n + " elements"); } else { print("not iterable"); } } Process([1, 2, 3]); // iterable, 3 elements Process((10, 20)); // iterable, 2 elements Process(42); // not iterable

Iterable a signature type (params and returns)

Iterable is also a usable signature type: a parameter declared as Iterable accepts any iterable, and a function declared to return Iterable may return any iterable. It works in named functions, fun/arrow lambdas, methods, and local functions. Passing a non-iterable argument or returning a non-iterable value is a typed runtime error (Expected an Iterable, got X.).

// A generic count helper accepts any iterable int ItCount(Iterable it) { var n = 0; foreach (var e in it) { n = n + 1; } return n; } print(ItCount([1, 2, 3])); // 3 array print(ItCount((1, 2, 3))); // 3 tuple print(ItCount("ab")); // 2 string var d = new Dictionary<string, int>(); d["a"] = 1; print(ItCount(d)); // 1 dict (enumerated as KeyValuePairs) print(ItCount([1, 2, 3].Where(fun (x) { return x > 0; }))); // 3 LINQ result print(ItCount(FpCoro2.pairs(3))); // 3 generator // A non-iterable argument is a typed runtime error try { ItCount(42); } catch (var ex) { print(ex.Message); } // Expected an Iterable, got Int32 // Iterable return type any iterable may be returned Iterable Range(int n) { var a = new int[n]; for (var i = 0; i < n; i = i + 1) { a[i] = i; } return a; } var s = 0; foreach (var x in Range(3)) { s = s + x; } print(s); // 3 array holding 0,1,2 // fun and arrow lambdas accept the same annotation var f = fun (Iterable it) { var n = 0; foreach (var e in it) { n = n + 1; } return n; }; print(f((1, 2))); // 2 var g = (Iterable it) => { var n = 0; foreach (var e in it) { n = n + 1; } return n; }; print(g([1, 2, 3])); // 3

RandomAccess indexable + re-enumerable contract

is/as RandomAccess is True for arrays, lists, tuples, and strings values that are both indexable (v[i]) and re-enumerable. It is False for dicts, HashSets, LINQ results, generators, and scalars. RandomAccess is a strict subset of Iterable: every RandomAccess value is iterable, but not every iterable is random access (dicts and LINQ results are single-pass). It is usable as a signature type too. typeof keeps the concrete type name (int[], Tuple, string, ...) never RandomAccess.

// is RandomAccess indexable + re-enumerable print([1, 2] is RandomAccess); // True array print((1, 2) is RandomAccess); // True tuple print("ab" is RandomAccess); // True string print(d is RandomAccess); // False dict is iterable but not random access var ra = [10, 20] as RandomAccess; if (ra != null) { print(ra[1]); } // 20 still indexable after the cast // RandomAccess-typed parameter index directly int First(RandomAccess ra) { return ra[0]; } print(First([5, 6])); // 5

Iterable combinators Replayable/Memoize, Tuple.Map/Fold, Iterable.* natives

Replayable(it) / Memoize(it) cache-once re-enumerable wrappers. A one-shot Iterable a coroutine generator, a LINQ result, a dict can only be enumerated once. Wrapping it in Replayable (alias Memoize) makes it re-enumerable: the first enumeration consumes the source and records each element as it is produced, and once it completes, every later enumeration replays the recorded elements. The cache grows with the number of elements enumerated.

// A coroutine generator is one-shot wrap it to enumerate twice namespace NumCoro { int nums(int n) { var i = 0; while (i < n) { yield i; i = i + 1; } return -1; } } var rp = Replayable(NumCoro.nums(3)); var s1 = 0; foreach (var p in rp) { s1 = s1 + p; } var s2 = 0; foreach (var p in rp) { s2 = s2 + p; } print(s1, s2); // 3 3 the wrapped generator replays // LINQ results are single-pass too Memoize caches them var rm = Memoize([1, 2, 3, 4].Where(fun (x) { return x % 2 == 0; })); var m1 = 0; foreach (var v in rm) { m1 = m1 + v; } var m2 = 0; foreach (var v in rm) { m2 = m2 + v; } print(m1, m2); // 6 6 print(rp is Iterable); // True the wrapper is itself an Iterable

Replayable/Memoize values are Disposable. A wrapper's cache is released deterministically: using (var r = Replayable(...)) { ... } (or the using var r = ... declaration form) calls r.Dispose() at block exit, and an explicit r.Dispose() works anywhere. Dispose() clears the cached elements and drops the wrapped source, so the memory is freed immediately; re-enumerating a disposed wrapper yields nothing (an empty sequence). Without a using or Dispose(), the cache lives until the wrapper is garbage-collected.

// Replayable/Memoize are Disposable dispose releases the cache and the source using (var r = Replayable(NumCoro.nums(3))) { var n = 0; foreach (var p in r) { n = n + 1; } print(n); // 3 first pass consumes the generator and caches it } // Dispose() runs here the cache and the source are released var rd = Replayable(NumCoro.nums(2)); var m = 0; foreach (var p in rd) { m = m + p; } // 0 + 1 = 1 rd.Dispose(); // deterministic release var m2 = 0; foreach (var p in rd) { m2 = m2 + p; } print(m, m2); // 1 0 re-enumeration after dispose is empty

Tuple.Map(tuple, fn) applies fn to every element and returns a tuple of the same arity with the element names preserved; Tuple.Fold(tuple, seed, fn) is an eager left fold the seed, then fn(acc, element) over each element in order. See the tuple entry for a names-preserved example.

// Tuple.Map same arity, element names preserved (int n, int m) src = (10, 20); var up = Tuple.Map(src, fun (x) { return x + 1; }); print(up.n, up.m); // 11 21 names survived the map print(typeof(up)); // Tuple still a concrete Tuple value var tot = Tuple.Fold((1, 2, 3), 0, fun (a, e) { return a + e; }); print(tot); // 6 left fold

The Iterable namespace adds FP combinators over any Iterable: Map, Filter, Fold, Zip, Append, Concat (an alias of Append) and Range plus ToList. Map/Filter/Zip/Append/Concat/Range are lazy (deferred) they return a re-enumerable result and run the function only as elements are pulled; Fold and ToList are eager. The first argument of every combinator is any Iterable; a non-iterable argument is a runtime error (Expected an Iterable, got X.). Iterable.Range(start, count) lazily yields start, start+1, ..., start+count-1 as ints. Iterable.ToList(it) eagerly copies any iterable into a new List<T> (copy semantics, like ToArray()); the element type is inferred when it is certain arrays use their element type and lists/sets use their ElementType, so Iterable.ToList([1, 2, 3]) is a List<int> and List<object> otherwise (tuples, strings, generators, dicts, LINQ results, mixed elements).

// Map lazy, re-enumerable; Filter keeps matching elements var sq = Iterable.Map((1, 2, 3), fun (x) { return x * 2; }); print(sq.Count()); // 3 var ev = 0; foreach (var v in Iterable.Filter((1, 2, 3, 4), fun (x) { return x % 2 == 0; })) { ev = ev + v; } print(ev); // 6 // Zip pairs up to the shorter source; Append/Concat join two Iterables var zp = 0; foreach (var p in Iterable.Zip((1, 2), (10, 20, 30), fun (a, b) { return a + b; })) { zp = zp + p; } print(zp); // 33 11 + 22, the longer source is clipped var ap = 0; foreach (var x in Iterable.Append((1, 2), (3, 4))) { ap = ap + x; } print(ap); // 10 // Fold is eager; Range is a lazy arithmetic sequence print(Iterable.Fold((1, 2, 3), 0, fun (a, e) { return a + e; })); // 6 var rg = 0; foreach (var x in Iterable.Range(5, 3)) { rg = rg + x; } print(rg); // 18 5 + 6 + 7 // ToList is eager and typed a fresh copy, not the source var tl = Iterable.ToList([1, 2, 3]); print(typeof(tl)); // List<int> typed when the element type is known print(typeof([1, 2, 3].ToList())); // List<int> the array method form print(typeof(Iterable.ToList("ab"))); // List<char> strings iterate as chars, like foreach

Namespace / type-name coexistence. The Tuple and Iterable namespaces live alongside the same-named type predicates: member access (Tuple.Map(...), Iterable.Zip(...)) resolves through the namespace objects, while is Tuple / is Iterable, as casts and typeof keep resolving through the type-name path unchanged.

// The same names stay valid as predicates and keep concrete typeof names print((1, 2) is Tuple); // True the predicate is unchanged var u = Tuple.Map((1, 2), fun (x) { return x; }); print(u is Tuple, typeof(u)); // True Tuple print([1, 2] is Iterable); // True try { Iterable.Map(42, fun (x) { return x; }); } catch (var ex) { print(ex.Message); } // Expected an Iterable, got Int32
// Every internal type: same name on all four surfaces + callable Dispose() var it = Sqlite.Query(db, "SELECT id, name FROM t"); print(it); // SqliteIterator print(typeof(it)); // SqliteIterator print(it is SqliteIterator); // True it.Dispose(); // real release never throws // Non-disposable natives are safe no-ops var dict = new Dictionary<string, int>(); dict.Dispose(); // no-op dict stays usable
Adding a new script-exposed internal type requires one entry in the central type registry (which drives is/typeof/print names) and, for a resource-owning type, a real Dispose(). The Script prefix is stripped automatically never expose it in script-facing names.

▼ Variables

var Implicitly-typed local variable

Type is inferred from the initializer expression. Must have an initializer.

var x = 42; // int var y = "hello"; // string
var a = 10; var b = 20; print(a + b); // Result: 30
A name holds ASCII letters, digits and underscore, plus the ACCENTED LATIN-1 letters. The accented range is the Latin-1 Supplement's letters (à to ö and ø to ÿ), so hé, café, Straße, niño and ação are ordinary names in a variable, a class, a property, a function and a dictionary key, and they travel into a compiled bundle. A character outside that range (CJK, Greek, Cyrillic) is not part of a name: it belongs inside a string or a comment, and the lexer refuses it with the rule in the message.
// accented names, the whole Latin-1 range var hé = 10; string Straße = "strasse"; class Été { public int Degré { get; set; } } print(hé + " " + Straße); // Result: 10 strasse
A KEYWORD cannot be a variable name, and @ is how a name that collides is kept. Writing var out = 1; is refused naming the keyword and the escape: @out is that name spelled so the parser sees an identifier, and the same holds for @when, @ref, @case and the rest. A handful of keywords are tolerant instead, and a variable may take one with a warning (var class = 5; works and says it may confuse a reader), so the refusal names the escape rather than a rule about all keywords.
// a keyword needs the @ escape var @out = 41; print(@out + 1); // Result: 42
// a keyword needs the @ escape var @out = 41; print(@out + 1); // Result: 42
typed declaration Explicit type declaration for variables

Types can be specified explicitly instead of using var.

int x = 42; string name = "Alice";
int x = 10; int y = 20; print(x + y); // Result: 30
const Immutable variable cannot be reassigned

Attempting to reassign a const variable throws ConstAssignment error.

const pi = 3.14159;
const rate = 0.05; var result = 1000 * rate; print(result); // Result: 50
destructuring Unpack array elements into multiple variables with var (a, b) = expr or [a, b] = expr

Destructuring unpacks an array or list into multiple variables in one statement. Two syntaxes are supported: parenthesized var (a, b) = expr for declarations, and bracket [a, b] = expr for assignments to existing variables.

var (a, b) = [10, 20]; // declares a and b [x, y] = source; // assigns to existing x, y
// Declaration destructuring var (first, second, third) = [1, 2, 3]; print(first); // 1 // Assignment destructuring [a, b] = [100, 200]; print(b); // 200 // With range literal [x, y] = 1..10; print(x); // 1
The source expression must evaluate to an array or list. The number of variables must not exceed the number of elements in the source.
tuple (a, b) Lightweight multi-value container (10, "hello"), named elements, destructuring

A tuple literal groups several values into one Tuple value. Tuples support positional access (t[0]), Item1..ItemN, Length, destructuring (var (a, b) = t), and Json.Serialize (as a JSON array). Element names come from the declared return type ((int i, string s)) or, for lambdas returning a matching-arity tuple, are inferred from the parameter names.

var t = (10, "hello", 3.5); (int i, string s) Fn() => (10, "hello");

1 · Basic literal, positional access, named elements, destructuring

// Tuple literal typeof, positional access, ItemN, Length, JSON array var t = (10, "hello", 3.5); print(t[0]); // 10 print(t.Item2); // hello print(t.Length); // 3 print(typeof(t)); // Tuple print(Json.Serialize(t)); // [10,"hello",3.5]
// Declared tuple return type → named elements (int i, string s) Test() => (10, "hello"); var r = Test(); print(r.i); // 10 print(r.s); // hello
// Lambda returning a tuple names inferred from the parameter names var mk = fun (int a, int b) { return (a, b); }; var p = mk(1, 2); print(p.a); // 1 print(p.b); // 2
// Destructuring with a discard var (x, _, z) = (1, 2, 3); print(x + z); // 4

Element access matrix

Tuple kindNamed accessPositional access
Declared return type (int a, int b) Fn()t.a, t.b ✅t[0], t.Item1 ✅
Lambda param-inferred (int a, int b) => { return (a, b); }t.a, t.b ✅t[0], t.Item1 ✅
Unnamed (int v) => { return (a, b); } (arity ≠ param count)t.a ❌ "Property not found"t[0] / t.Item1 / t.Length ✅

2 · Advanced tuple parameters, tuple returns, namespaces, classes, coroutines

Functions, lambdas (fun and => arrow forms), methods, local functions and coroutines can declare a tuple parameter. In the unnamed form the element names become usable directly in the body; in the named form the parameter name binds the whole tuple and elements resolve via name.field.

// Tuple parameters unnamed: elements usable directly in the body var sum = fun ((int n, int m)) { return n + m; }; print(sum((3, 4))); // 7 // Arrow form var mul = ((int n, int m)) => n * m; print(mul((5, 6))); // 30 // Named form the name binds the tuple; elements via name.field var diff = fun ((int a, int b) p) { return p.a - p.b; }; print(diff((9, 4))); // 5 // Named function + namespace + method + coroutine forms are all supported
// Tuple-typed variable declaration declared element names bind directly (int c, int d) name = (10, 20); print(name.c); // 10 print(name.d); // 20
// Functions and lambdas RETURNING tuples (int, int) Tp() { return (21, 2); } print(Tp()[0]); // 21 unnamed return, positional access (int a, int b) LocalPair(int v) { return (v, v * 2); } print(LocalPair(21).a); // 21 named return accessed inline // Recursive fibPair-style a tuple-param lambda returning a 2-tuple var fibPair = fun ((int n)) { if (n <= 1) return (n, 1); var prev = fibPair((n - 1)); return (prev[1], prev[0] + prev[1]); }; var fp = fibPair((10)); print(fp[0]); // 55 print(fp[1]); // 89
// Tuples in namespaces and classes namespace functions take AND return tuples namespace Geo { (int x, int y) Shift((int a, int b) p, int dx) { return (p.a + dx, p.b + dx); } } var g = Geo.Shift((1, 2), 10); print(g.x); // 11 print(g.y); // 12 // Class methods take tuple params; a method returns a tuple via `object` + (Tuple) cast class Pt { public int Sum((int a, int b) p) { return p.a + p.b; } public object Get() { return (3, 4); } } var pt = new Pt(); print(pt.Sum((10, 32))); // 42 var tgt = (Tuple)pt.Get(); print(tgt[0]); // 3
// Coroutines yielding tuples direct generator path namespace PairCoro { int pairs(int n) { var i = 0; while (i < n) { yield (i, i * 2); i = i + 1; } return -1; } } var gen = PairCoro.pairs(2); print(gen.MoveNext(), gen.Current[0], gen.Current[1]); // True 0 0 print(gen.MoveNext(), gen.Current[0], gen.Current[1]); // True 1 2 print(gen.MoveNext()); // False // ... or destructure the yielded tuple var gen2 = PairCoro.pairs(1); gen2.MoveNext(); var (a, b) = gen2.Current; print(a, b); // 0 0
// A tuple-param lambda passed as a Func<object,int> argument namespace ApplyNs { int Apply(Func<object, int> fn) { return fn((3, 4)); } } print(ApplyNs.Apply(fun ((int n, int m)) { return n + m; })); // 7

Type check is Tuple

In a script the tuple type is addressed as Tuple, which is also what typeof reports. Use is Tuple to test whether a value is a tuple, and inspect .Length / .Names:

string describe(object v) { if (v is Tuple) { var t = (Tuple)v; return "tuple(" + t.Length + ")" + (t.Names == null ? "" : " " + string.Join(",", t.Names)); } return "not a tuple"; } print(describe((1, 2))); // tuple(2) (int a, int b) Pair() => (1, 2); print(describe(Pair())); // tuple(2) a,b print(describe(42)); // not a tuple

Tuple.Map / Tuple.Fold element-wise combinators

Tuple.Map(tuple, fn) applies fn to every element and returns a tuple of the same arity with the element names preserved; Tuple.Fold(tuple, seed, fn) is an eager left fold the seed, then fn(acc, element) over each element in order. See the Internal Types → Iterable combinators block for the full reference.

// Tuple.Map same arity, names preserved (int a, int b) src = (10, 20); var mapped = Tuple.Map(src, fun (x) { return x + 1; }); print(mapped.a, mapped.b); // 11 21 names preserved through the map print(mapped is Tuple); // True still a Tuple value // Tuple.Fold left fold: 1 + 2 + 3 print(Tuple.Fold((1, 2, 3), 0, fun (a, e) { return a + e; })); // 6

3 · Edge cases

// Arity mismatch on a tuple-param bind runtime error var f1 = fun ((int n, int m)) { return n + m; }; f1((1, 2, 3)); // ✗ Parameter '__tup0' expects a 2-element tuple, got 3 elements // Non-tuple argument to a tuple param runtime error f1([1, 2]); // ✗ Parameter '__tup0' expects a tuple argument, got 'Int32[]' // Destructuring is LENIENT on arity extra elements are dropped; a missing element stays unbound var (x, y) = (1, 2, 3); // x = 1, y = 2 no error var (u, v, w) = (7, 8); // w is NOT bound using it is an "Undefined variable 'w'" error var (a, b) = 42; // ✗ Cannot destructure type 'Int32'. Expected array or list
Destructuring also works in two new positions: foreach (var (a, b) in items) destructures each iteration item (tuple / array items, coroutine yields, dictionary KeyValuePair items a → Key, b → Value), and match tuple patterns case (int a, int b) => ... bind the element names in an arm-scoped scope. See the foreach and match entries.
// Unnamed tuples expose ItemN / [0] only named access is a runtime error var plain = (7, 8); print(plain.Item1); // 7 plain.a; // ✗ Property 'a' not found on tuple
// Nested tuples each element is itself a tuple var nst = (1, (2, 3)); print(nst[0]); // 1 print(nst[1][0]); // 2 print(nst[1].Length); // 2
// Tuples inside lists and dictionaries var lst = [(1, 2), (3, 4)]; print(lst[1][0]); // 3 var d = new Dictionary<string, object>(); d["k"] = (9, 10); print(((Tuple)d["k"])[1]); // 10
// A tuple param inside a coroutine namespace CoroEdge { int gen((int a, int b) p) { yield (p.a + p.b, p.a - p.b); return -1; } } var eg = CoroEdge.gen((9, 4)); print(eg.MoveNext(), eg.Current[0], eg.Current[1]); // True 13 5
// Engine edge a tuple-param element name colliding with a global is misdetected // as an external capture (the prologue-destructured element isn't registered as a // lambda parameter). Results stay correct the element still wins but the lambda // takes a full closure snapshot instead of the shared capture-free one. var n = 100; // a global `n` ... var f = fun ((int n, int m)) { return n + m; }; print(f((3, 4))); // 7 the tuple element wins over the global
Tuple parameters are supported in functions, lambdas, methods and local functions. Delegates, constructors and operator overloads reject tuple parameters with a parse error (Tuple parameters are not supported in this context.) such declarations have no body to destructure into.
Tuple element names exist only when declared ((int i, string s) Fn()) or inferred from matching lambda parameters. An undeclared tuple like () => (10, "hello") exposes Item1..N / [0] only. Tuples run in both the tree interpreter and the bytecode VM (MAKE_TUPLE).

▼ Control Flow

if/else Conditional branching

Executes thenBranch if the condition is truthy, elseBranch otherwise.

if (condition) { /* then */ } else { /* else */ }
if (x > 10) { print("large"); } else { print("small"); }
using Resource acquisition and automatic disposal

The using statement acquires a disposable resource, executes a block of code, and then disposes the resource even if an exception occurs. The variable declared in the using expression is scoped to the block and disposed when the block exits.

using (var f = Application.CreateForm("MyForm")) { // use f inside the block f.Width = 300; } // f.Dispose() called automatically, even on exception
using var b = Mem.Buffer(64); // declaration form no block; disposed at enclosing scope exit
// Declaration form (C# semantics): the resource lives until the enclosing scope exits void work() { using var b = Mem.Buffer(200 * 1024 * 1024); Mem.Fill(b.Ptr, 200 * 1024 * 1024, 0xFF); print(Mem.ReadByte(b.Ptr, 0)); // 255 } // b disposed here no explicit Mem.Free / b.Dispose() needed

A top-level using var is disposed when the run ends, because there is no enclosing block to leave. In a file that is the end of the program; at the REPL each line is a run, so the resource is released before the next line is read. The block form disposes at its own } wherever it appears, which is the one to reach for when the release has to be observed.

The forms are using (var x = init) { }, using var x = init;, and using (expression) { } for a resource you already hold: the expression is evaluated once and bound to a name the body cannot see. await using spells the same three shapes for a resource that implements IAsyncDisposable, and awaits the disposal: await using (var x = init) { }, await using var x = init;, await using (expression) { }.

await using (var lines = File.ReadLinesAsync("data.csv")) { await foreach (var line in lines) { print(line); } } // DisposeAsync awaited when the block exits, even on exception

Which one a value needs is the interface it implements, and a mismatch is refused by name rather than silently doing nothing: a value implementing only IDisposable under await using is told to write using, one implementing only IAsyncDisposable under using is told to write await using, and a value implementing neither is refused too. A disposal that cannot be observed is worth knowing about: a CLR async sequence opens its file when it is created, so a sequence that is created and never enumerated holds it, and the same is true after disposing that sequence by hand.

// With a form (implements IDisposable) using (var form = Application.CreateForm("Demo")) { form.Width = 400; form.Height = 300; } // form.Dispose() called automatically // Nested using blocks using (var f1 = Application.CreateForm("Outer")) { using (var f2 = Application.CreateForm("Inner")) { print(f2.Width); } // inner disposed } // outer disposed // With a script class destructor class Resource { int id; public Resource(int v) { id = v; } ~Resource() { print("cleanup " + id); } } using (var r = new Resource(1)) { print("using resource"); } // ~Resource() runs here
Which types support using?
  • IDisposable .NET types: Form, StreamWriter, MemoryStream, TcpClient, ProcessHandle (via is IDisposable)
  • Script class instances with ~Destructor() the destructor chain runs on block exit
  • Any object with a Dispose() method resolved via duck-typing reflection fallback
while Loop while condition is truthy

Coroutine-aware supports suspension and resumption at any point inside the loop body.

while (condition) { /* body */ }
var i = 0; while (i < 5) { i = i + 1; } print(i); // Result: 5
for C-style for loop with initializer, condition, and increment

Coroutine-aware supports suspension inside the loop body. The increment expression runs after each iteration.

for (init; condition; increment) { /* body */ }
var sum = 0; for (var i = 0; i < 10; i = i + 1) { sum = sum + i; } print(sum); // Result: 45
foreach Iterate over collections, arrays, coroutines

Supports any Iterable arrays, lists, tuples, dicts, HashSets, LINQ results, generators, and strings. Coroutine-aware.

Dictionary iteration: foreach(var kv in dict) yields KeyValuePair objects, and KeyValuePair(key, value) builds one (the same bare-call shape Rect(l, t, r, b) has, since a bare new KeyValuePair(a, b) reaches the CLR generic and cannot infer its type arguments). Access the key via kv.Key and the value via kv.Value. This works on native Dictionary<K,V>, script Dictionary<K,V>, and the boxed rows a sqlite cursor yields.

foreach (var item in collection) { /* body */ }
var nums = new List<int>(); foreach (var n in nums) { print(n); }

Destructuring form: foreach (var (a, b) in items) destructures each iteration item into the given names over tuple items, array items, coroutine yields, and dictionary KeyValuePair items (a → Key, b → Value). A non-destructure-able item (e.g. a plain int) is a runtime error.

// foreach destructuring tuples and arrays var total = 0; foreach (var (a, b) in [(1, 2), (3, 4)]) { total += a + b; } // total = 10 foreach (var (x, y) in [[1, 2], [3, 4]]) { total += x * y; } // total = 24 array items // ... and over coroutine yields foreach (var (n, m) in PairCoro.pairs(3)) { csum += n; } // csum = 3 // A non-destructure-able item is a runtime error foreach (var (u, v) in [1, 2]) { } // ✗ Cannot destructure type 'Int32' ...

Tuples & enumeration

LINQ results: a filtered (or otherwise LINQ-produced) tuple sequence enumerates like any other collection use the plain form, or the destructuring form over the filtered items.

// (1) Filter a tuple list with Where, then enumerate foreach (var t in [(1, 2), (3, 4), (5, 6)].Where(fun (t) => t[0] > 1)) { print(t[0], t[1]); // 3 4 / 5 6 (1, 2) filtered out } // The destructuring form works over the filtered result too var total = 0; foreach (var (a, b) in [(1, 2), (3, 4), (5, 6)].Where(fun (t) => t[0] > 1)) { total += a + b; } print(total); // 18 (3+4 + 5+6)

break / continue behave normally inside the destructuring form.

// (2) break / continue in a destructuring foreach var sum = 0; foreach (var (a, b) in [(1, 2), (3, 4), (5, 6), (7, 8)]) { if (a == 3) continue; // skips (3, 4) if (a == 7) break; // exits before (7, 8) sum += a + b; } print(sum); // 14 (1+2 + 5+6)

Bare tuple iteration

// A bare tuple iterates element-wise yields 1, 2, 3 var ts = 0; foreach (var x in (1, 2, 3)) { ts = ts + x; } print(ts); // 6 // Named tuples iterate the same way yields 10, 20 (int p, int q) pair = (10, 20); var psum = 0; foreach (var v in pair) { psum = psum + v; } print(psum); // 30 // A tuple-of-tuples iterates its inner tuples yields (1, 2), (3, 4) foreach (var t in ((1, 2), (3, 4))) { print(t[0], t[1]); } // 1 2 / 3 4 // The destructuring form works over the inner tuples too var s = 0; foreach (var (u, w) in ((1, 2), (3, 4))) { s = s + u + w; } print(s); // 10
foreach (var (k, v) in dict) destructures each KeyValuePair the iteration item is a KeyValuePair, destructured as k → Key and v → Value. This works on native Dictionary<K,V>, script Dictionary<K,V>, and the boxed rows a sqlite cursor yields. The same destructuring also works in statement form: var (k, v) = kv;. Use kv.Key / kv.Value when you need the pair object itself, as shown under Dictionary iteration above.

Coroutine yields (single-var form): a coroutine's yielded values enumerate generator-style in foreach or drive the coroutine directly with MoveNext() / Current.

// (5) generator-style enumeration of coroutine yields namespace Gen { int nums(int n) { var i = 0; while (i < n) { yield i * 2; i = i + 1; } return -1; } } foreach (var x in Gen.nums(3)) { print(x); } // 0 2 4 // Direct driver loop MoveNext() / Current var co = Gen.nums(2); while (co.MoveNext()) { print(co.Current); } // 0 2 see the Coroutine entry

Async streams (await foreach)

An asynchronous sequence (IAsyncEnumerable<T>) produces its elements one await at a time, so it is read with await foreach. A plain foreach over one is refused, and the refusal says what to write: Cannot iterate over an asynchronous sequence of string with a plain foreach: its elements arrive one await at a time, so write `await foreach (var item in …)`. await foreach over something that is NOT asynchronous is refused too, naming the type that has no GetAsyncEnumerator.

await foreach (var line in asynchronousSequence) { /* body */ }

It is allowed in the same two places an await is: at the top level of a file (where the engine waits for each element, the way an async entry point does) and inside an async function. break and continue behave normally, and the sequence is disposed on every exit, including a break out of the loop, so a file handle is released.

// Read a file line by line, stopping after the header var n = 0; await foreach (var line in File.ReadLinesAsync("data.csv")) { if (n++ == 10) { break; } print(line); } async Task<int> CountLines(string path) { var total = 0; await foreach (var line in File.ReadLinesAsync(path)) { total = total + 1; } return total; }
A source-less bundle carries such a file's source: an await foreach runs on the tree walker, because the bytecode VM has no state for an async enumerator, so --compile --no-source refuses that file by name and the default (source carried) behaves as the script does. The same is true of a match pattern only in the opposite direction: patterns DO travel now (as their own source text), see the Bytecode entry.
break Exit the current loop immediately

Works inside while, for, and foreach loops. Coroutine-safe.

break;
var i = 0; while (true) { if (i >= 3) break; i = i + 1; } print(i); // Result: 3
continue Skip to the next iteration of the current loop

Works inside while, for, and foreach loops.

continue;
var sum = 0; var i = 0; while (i < 5) { i = i + 1; if (i == 3) continue; sum = sum + i; } print(sum); // Result: 12 (skips 3: 1+2+4+5)
match Pattern matching expression compare a value against multiple patterns

The match expression compares a subject value against a series of patterns, returning the value associated with the first matching pattern. Patterns are separated by commas, and a wildcard _ pattern matches everything (must be the last arm).

Two equivalent forms are supported: the postfix form subject match { ... } and the prefix form match (subject) { ... }. The case keyword before a pattern is optional in both forms.

Patterns: a match arm uses exactly the same pattern grammar as switch constants, wildcard _, type patterns with an optional binding, relational patterns, tuple patterns, logical (and/or/not, with (…) grouping), property patterns and list patterns. An arm may add a guard with when expr, evaluated after the pattern's bindings are in scope.

// type patterns, bindings, guards and logical/property/list patterns all work in match var r = o match { int n when n > 0 => "positive", int and > -100 => "other int", { Name: "bob" } => "bob", [1, ..] => "starts with 1", _ => "other" };
expr match { 1 => "one", 2 => "two", _ => "other" }
// Matching integers var status = 404; var label = status match { 200 => "OK", 404 => "Not Found", _ => "Unknown" }; print(label); // "Not Found" // Matching strings var level = "warn" match { "error" => 500, "warn" => 400, _ => 200 }; print(level); // 400 // With enum enum Http { OK=200, NotFound=404 } var name = Http.NotFound match { 200 => "OK", 404 => "Not Found", _ => "?" };

Tuple patterns

A tuple pattern case (int a, int b) => ... matches the subject on tuple-ness + arity: the subject must be a tuple with exactly that many elements. The element types are informational (not checked); only the shape matters. The element names bind in an arm-scoped scope visible in that arm's value expression only, never after the match. _ is a discard (binds nothing), and unnamed elements case (int, int) are a shape check with no bindings. On a mismatch (non-tuple subject or wrong arity) the arm is skipped and matching falls through to the next arm.

// Tuple patterns prefix and postfix forms, optional `case` var r1 = match (1, 2) { case (int a, int b) => a + b, _ => 0 }; // 3 prefix form, with `case` var r2 = (1, 2) match { (int a, int b) => a + b, _ => 0 }; // 3 postfix form, `case` omitted var shape = (1, 2) match { (int, int) => "2-tuple", _ => "other" }; // "2-tuple" shape check, no bindings var d = (1, 2) match { case (int _, int b) => b, _ => 0 }; // 2 `_` is a discard var f = match "x" { case (int a, int b) => 1, _ => 7 }; // 7 non-tuple subject falls through var g = match (1, 2, 3) { case (int a, int b) => 99, _ => -1 }; // -1 arity mismatch falls through // Arm-scoped names: `a` and `b` are undefined after the match no leakage

Samples tuples in real flows

Tuple patterns shine where real code produces tuples: function return values, foreach destructuring pipelines, namespace functions, and mixed pattern arms. match arms do not support when guards (unlike switch), so a conditional arm uses a value pattern on the relevant element instead.

// (1) Match on a tuple returned by a function (int, int) Pt() { return (3, 4); } var m = match Pt() { case (int a, int b) => a + b, _ => 0 }; print(m); // 7 // (2) foreach + match pipeline the arm is a value pattern (match arms have no `when` guard) var labels = new List<string>(); foreach (var (a, b) in [(1, 2), (7, 8)]) { labels.Add(match b { 8 => "eight", _ => "other" }); } print(labels[0], labels[1]); // other eight // (3) Tuples from a namespace function, matched with tuple patterns namespace Geo { (int, int) Origin() { return (0, 0); } (int, int) Offset() { return (5, 6); } } var sum = match Geo.Origin() { case (int x, int y) => x + y, _ => -1 }; var prod = match Geo.Offset() { case (int x, int y) => x * y, _ => -1 }; print(sum, prod); // 0 30 // (4) A tuple-pattern arm combined with value patterns on the same subject var combo1 = match 0 { 0 => "zero", case (int a, int b) => a + b, _ => "other" }; // "zero" the value pattern wins on an int subject var combo2 = match (5, 6) { 0 => "zero", case (int a, int b) => a * b, _ => "other" }; // 30 the tuple arm handles a tuple subject print(combo1, combo2); // zero 30 // (5) Nested tuple patterns are NOT supported `case (int, (int, int))` is a parse error. // Patterns are flat: shape is tuple-ness + arity only, so a nested-tuple VALUE matches a flat pattern. var nested = match ((1, 2), 3) { case (int, int) => "pair", _ => "other" }; print(nested); // pair
match is a soft keyword: a function literally named match that is called and followed by a block match(x) { ... } parses as a match expression (subject x), not a call. Without the block, match(x) still resolves to the identifier/function.
The last arm must be a wildcard _ to ensure exhaustive matching. Patterns are compared using == (equality).
case / when A switch label, and the guard that narrows it

case introduces a label in a switch statement or expression, and when adds a GUARD to it: the label only matches when the guard is truthy, which is how one case covers several values without repeating its body. default is the label that matches when nothing else did, and a match arm takes the same guard (pattern when cond => value). The switch and match entries have the rest (patterns, several labels on one arm, the wildcard a match expression requires).

var n = 3; var label = ""; switch (n) { case 1: label = "one"; break; case 3 when n > 2: label = "three"; break; default: label = "other"; break; } print(label); // three print(5 match { > 3 when true => "big", _ => "small" }); // big
switch C#-style switch statement with pattern matching constant, type, var, when guards

Pattern kinds (shared by switch, match and is): constant (1, "x", null), wildcard _, var name, type (int, string) with optional binding (int n), relational (> 5, <= 0), logical (p and q, p or q, not p, grouped (p)), tuple ((int a, int b)), property ({ Name: "bob", Age: > 18 } instances, dictionaries by key, named tuples by element name; an unknown member is a non-match), list ([1, 2], [1, ..], [.., 3], [1, .., 9], [1, .. var rest], [1, .. _] subjects are arrays, Lists, tuples and strings, whose elements are chars ("abc" is ['a','b','c'] is true; ["a", ..] is not, since a char is not a 1-character string); one slice max; the .. var rest capture follows the subject kind a List yields a List (element type preserved), a string yields char[], arrays/tuples yield an array; .. _ is an explicit discard). Binding rules: a name may be bound once per pattern; both sides of or must bind the same names; is bindings live only in an if/while true branch. Diagnostics (warnings, never errors): a switch with no _/default arm warns as non-exhaustive, an arm placed after a wildcard warns as unreachable, and two structurally equal constant arms warn as duplicates (1 vs 1 collides; 1 vs 1L does not).

The switch statement evaluates a subject expression and executes the first matching case. Supports constant patterns, type patterns with binding (case int i:), var patterns (case var v:), discard (case _: / default:), when guards, and multiple labels (case 1: case 2:). No fallthrough each case must exit via break or return.

Also available as a switch expression (expr switch { pattern => value, ... }), returning a value from the first matching arm.

Switch statement

switch (expr) { case 1: return "one"; case 2: return "two"; default: return "other"; }
// Constant patterns int test1(int x) { switch (x) { case 1: return 10; case 2: return 20; default: return 0; } } // Type patterns with binding string test3(object x) { switch (x) { case int i: return "int: " + i; case string s: return "str: " + s; default: return "other"; } } // When guard string test4(int x) { switch (x) { case int i when i < 0: return "negative"; case int i when i == 0: return "zero"; case int i: return "positive: " + i; } return ""; } // Multiple labels share one body int test7(int x) { switch (x) { case 1: case 2: case 3: return 123; default: return 0; } } // Break exits the switch (not surrounding loop) int test9() { var sum = 0; var i = 0; while (i < 10) { i = i + 1; switch (i) { case 3: break; // exits switch, loop continues case 5: break; // exits switch, loop continues default: sum = sum + i; } } return sum; // 1+2+4+6+7+8+9+10 (skipped 3,5) }

Switch expression

return x switch { 1 => "one", 2 => "two", _ => "other" };
// Switch expression with constant + discard int test8(int x) { return x switch { 1 => 11, 2 => 22, _ => 0 }; } // With when guard in expression var label = code switch { 200 => "OK", 404 => "Not Found", int c when c > 500 => "server error", _ => "unknown" }; // Lambda shorthand (o) => o switch { ... } var classify = (o) => o switch { int i when i < 0 => "negative", int i => "int: " + i, string s => "str: " + s, _ => "other" }; print(classify(42)); // "int: 42" print(classify("hi")); // "str: hi"

Pattern reference

PatternSyntaxExample
Constantcase value:case 42:, case "hello":
Type (no bind)case Type:case int:, case string:
Type (with bind)case Type name:case int i: i usable in body
Varcase var name:case var v: always matches, binds to v
Discardcase _: / default:Catch-all matches anything
When guardcase pattern when cond:case int i when i > 0:
Multiple labelscase A: case B:case 1: case 2: case 3: body
Named .NET type patterns
Callablescase Function:Matches script function values
case Coroutine:Matches running coroutines
Delegate typescase Delegate:Matches any .NET delegate
case Func:Matches Func<> instances
case Action:Matches Action<> instances
case Predicate:Matches Predicate<T> instances
System typescase Regex:Matches Regex objects
Break semantics: break; inside a switch exits the switch, not the surrounding loop. If no switch is active, break exits the innermost loop as usual.
return Return a value from a function

In void functions, return; without a value is allowed. Returning a value from a void function is an error.

A returned value is coerced to the function's declared return type, as in C#: an int function returning 2.5 gives 2, and a value the declared type cannot hold is refused (Cannot convert string 'hi' to int) rather than travelling on unchanged. A coroutine is the exception: return in a generator supplies the generator's final value, which the coroutine API hands back as it is, so a yield-based body is not constrained by the declared type.

return value;
int square(int x) { return x * x; } print(square(7)); // Result: 49

⚡ return.Value inspect the pending return inside finally

Inside a finally block, return.Value reads the value that is about to be returned from the enclosing try. This is a super power compared to C#: C# finally cannot observe the return value without an extra local variable, and return inside a C# finally is a compile-time error.

return.Value
// ⚡ finally can inspect the pending return value int testFinallyReturn() { try { return 42; } finally { var retVal = return.Value; print("Finally runs before return, value is: " + retVal); } } print(testFinallyReturn()); // Output: // Finally runs before return, value is: 42 // 42

⚡ return inside finally overrides the pending value

Unlike C# (which forbids return inside finally), ScriptLangCore allows it. A return executed inside a finally block replaces the original pending return value. Any nested finally still runs and sees the new value.

// ⚡ return in finally overrides the original return int testOverrideReturn() { try { return 42; } finally { print("First finally sees: " + return.Value); return 77; // overrides 42 → function returns 77 } } print(testOverrideReturn()); // Output: // First finally sees: 42 // 77
// Nested try/catch/finally inside finally return.Value is read-only at runtime int testNestedFinally() { try { return 42; } finally { try { return.Value = 15; print("(0)Finally runs before return: " + return.Value); } catch { print("(1a)Finally runs before return: " + return.Value); return 77; print("(1b)Finally runs before return: " + return.Value); } finally { print("(2)Finally runs before return: " + return.Value); } } } print(testNestedFinally()); // Output: // (1a)Finally runs before return: 42 // (2)Finally runs before return: 77 // 77

Notes:

  • return.Value is only meaningful inside a finally block whose corresponding try contains a return. Outside that context, it is null.
  • return.Value is read-only at runtime assigning to it throws a ScriptException with the message "Cannot assign to 'return.Value' it is read-only.". This exception is catchable by a wrapping try/catch.
  • A return statement inside a finally block overrides the pending return value. The function returns the last value returned, regardless of the original return in the try.
  • Nested finally blocks always run before the function actually returns, and they see the latest pending return value at the moment of execution.
  • At the top level a return ends the script and its value becomes the RUN'S ANSWER, which is ScriptResult.ReturnValue: what RunScript hands a script, what slc_file puts in the JSON it answers, and what the ABI reports. A bare return; answers nothing, a statement written after it never runs, and a return inside an if ends the run there. The value is NOT the process exit code: that comes from exit(n), abort(n) or an exitcode = n assignment (return 42; leaves the process at 0, while exitcode = 7; return 0; leaves 7). A script that ends without an explicit return exits with code 0, and one that encounters an unhandled error exits with 1.

⚡ return at the top level is the run's answer

The top level is a body like any other for return, so a script answers with an explicit value instead of trailing an expression statement. That matters where the answer is a result rather than a printed line: RunScript(file) reads .ReturnValue, slc_file(path) serializes it into the JSON it returns, and a host reading the ABI's verdict gets the same value.

// the same file, five shapes, and what the run answers return "blub"; // ReturnValue: "blub" (a statement after it does not run) return 42; // ReturnValue: 42 return { ok: true, n: 7 }; // ReturnValue: {"ok":true,"n":7} if (done) { return "early"; } // ends the run there, the rest of the file never runs 1 + 2; // no return at all: the last expression statement is the answer, 3 return; // answers nothing: the JSON has no ReturnValue member

Any value travels: a scalar, a string, a list, a dictionary literal, a struct or a class instance (its fields become the document), and a list of instances inside one. What does NOT travel is a computed member: a method is not serialized and the language has no computed property, so a summary you want in the answer is a FIELD you fill before returning.

That makes a script a small report factory: run each step, record what happened, and answer with the whole log in one value.

class StepLog { public string Name; public string State = "pending"; public string Detail = ""; } class RunLog { public string Suite; public string Verdict = "pending"; public List<StepLog> Steps = [].ToList(); public void Add(string name, string state, string detail) { var s = new StepLog(); s.Name = name; s.State = state; s.Detail = detail; this.Steps.Add(s); } public long Count(string state) { var n = 0; foreach (var s in this.Steps) { if (s.State == state) { n = n + 1; } } return n; } } // one step: run it, record it, and never let a failure end the run RunLog Step(RunLog log, string name, Func<int> work) { try { var code = work(); if (code == 0) { log.Add(name, "passed", ""); } else { log.Add(name, "failed", "exit " + code); } } catch (var ex) { log.Add(name, "failed", ex.Message); } return log; } var log = new RunLog(); log.Suite = "nightly"; Step(log, "compile", fun() { return 0; }); Step(log, "unit", fun() { return 2; }); Step(log, "smoke", fun() { throw "no database beside the exe"; }); log.Add("publish", "skipped", "no credentials"); if (log.Count("failed") > 0) { log.Verdict = "failed"; } else { log.Verdict = "passed"; } print("nightly: " + log.Count("passed") + " passed, " + log.Count("failed") + " failed"); return log; // the whole report is the run's answer

The run answers one document, so the reader queries it instead of parsing lines: json_extract(slc_file(path), '$.ReturnValue.Verdict') is the verdict, and json_each turns the log into rows (select value from json_each(slc_file(path), '$.ReturnValue.Steps') where json_extract(value, '$.State') = 'failed' gives the failures). The same file answers .ReturnValue through RunScript, and the example strips, so a bundle answers it too.

Two boundaries are worth knowing before relying on it. A typed line in the REPL is not a run: return 5; at the prompt echoes = 5 and the session continues, where the same line in a file ends the script. And the answer is not the exit code, so a script whose answer says "failed" still exits 0 unless it says otherwise with exitcode.

debugger A breakpoint you can leave in the source

debugger; is a statement that hands control to the script debugger when it is on (.debug), and does nothing at all when it is off. That is what makes it safe to leave in a script: a normal run, a compiled bundle and every suite step straight past it, and the same line becomes a breakpoint for the session in which the debugger is on. It takes no arguments and needs its semicolon.

var total = 0; while (total < 3) { total = total + 1; debugger; // stops here only while .debug is on } print(total); // 3
do/while Execute loop body at least once, then repeat while condition is truthy

The do keyword introduces a loop that executes its body once unconditionally, then repeats while the condition remains truthy. The while keyword and condition appear after the body.

do { /* body */ } while (condition);
var i = 0; do { i = i + 1; } while (i < 5); print(i); // Result: 5 // Always runs at least once, even if condition is false var x = 10; do { x = x + 1; } while (x < 5); print(x); // Result: 11

▼ Functions

fun / arrow lambda Anonymous function expression (lambda) fun syntax or C#-style (args) => expr / x => expr

Lambdas capture their enclosing scope (closure). Two syntaxes are available: the fun keyword, and the C#-style (args) => expr form (no fun keyword). Both produce the same AST and behave identically. The arrow takes an expression or a block body; with the keyword, => takes an expression and a block is written in braces with no arrow, and the keyword form is the only one that can be async. The table below lists every spelling, with what it accepts.

// fun keyword (explicit types) fun (int x) => x * 2; fun (int x) { return x * 2; } // C#-style arrow (types optional, default object?) (x) => x * 2; (x) => { return x * 2; } () => 42; (int x, int y) => x + y; // C#-style bare single parameter (parens optional for exactly one untyped param) x => x * 2; x => { var n = x * 2; return n + 1; };
// fun keyword with expression body var dbl = fun (int x) => x * 2; print(dbl(21)); // 42 // Same lambda with C#-style arrow (type inferred as object?) var dbl2 = (x) => x * 2; print(dbl2(21)); // 42 // Zero parameters var answer = () => 42; print(answer()); // 42 // With closure var mult = 10; var adder = (int x) => x + mult; print(adder(50)); // 60 // Block body var abs = (x) => { if (x >= 0) return x; return -x; }; print(abs(-5)); // 5 // Higher-order function with arrow callback var nums = [1, 2, 3]; var doubled = [x*2 for x in nums]; print(doubled[0]); // 2 // Bare single-parameter form same lambda without parens (C#-style, untyped param) var sq = x => x * x; print(sq(5)); // 25 // Block body, bare form var twice = x => { var n = x * 2; return n + 1; }; print(twice(5)); // 11 // LINQ with bare lambda hs10.Select(x => x * 2).Count() == 4 var hs = new HashSet<int>(); hs.Add(1); hs.Add(2); hs.Add(3); hs.Add(4); print(hs.Select(x => x * 2).Count()); // 4
// Verified coverage bare single-parameter arrow lambdas (from iterable_test.slc, group 11) Check("11a. LINQ bare lambda: hs10.Select(x => x * 2).Count() == 4", hs10.Select(x => x * 2).Count() == 4); var f11 = x => x * 2; Check("11b. bare expr lambda: f = x => x * 2; f(5) == 10", f11(5) == 10); var g11 = x => { var n = x * 2; return n + 1; }; Check("11c. bare block lambda: g = x => { ... }; g(5) == 11", g11(5) == 11); Check("11d. chained bare lambdas: [1,2,3].Select(x => x + 1).Where(y => y > 2).Count() == 2", [1,2,3].Select(x => x + 1).Where(y => y > 2).Count() == 2); Check("11e. bare lambda on tuple: (1,2,3).Select(x => x * 3).Count() == 3", (1, 2, 3).Select(x => x * 3).Count() == 3); VmSetEnabled(false); var treeCount11 = [1,2,3].Select(x => x * 5).Count(); VmSetEnabled(true); Check("11f. bare lambda tree-mode parity: Select(x => x * 5).Count() == 3", treeCount11 == 3); Check("11g. discard lambda: [1,2].Select(_ => 7).Count() == 2", [1,2].Select(_ => 7).Count() == 2); var five11 = 5; Check("11h. match bare-identifier PATTERN still a pattern (suppression): 5 match { five11 => \"yes\", _ => \"no\" } == \"yes\"", (5 match { five11 => "yes", _ => "no" }) == "yes");

Which spelling does what

Both syntaxes make the same value, and they differ in which body each one accepts. An ARROW takes an expression or a block; the fun keyword takes an expression after =>, or a block in braces with no arrow at all; and only the keyword form can be async.

SpellingAcceptedWhat it is
(int x, int y) => x + y✅expression body, typed parameters
(string a, string b) => { return a + b; }✅block body with the arrow (no fun)
x => x * 2
x => { ... }
✅a bare single UNTYPED parameter: the parentheses are optional, with either body
() => 42
() => { ... }
✅no parameters
fun (int x) => x * 2✅expression body with the keyword
fun (int x) { return x * 2; }✅block body with the keyword: BRACES, no arrow
fun (int x) => { return x * 2; }❌ Refusedthe keyword form's => takes an expression only, so a block is written with braces and no arrow. The refusal says so: Cannot use '=>' with block body '{ ... }'. Use 'fun () { ... }' for block body or 'fun () => expr' for expression body.
async fun (string p) { ... await ... }✅an async lambda with a block body, which is the spelling a body that awaits needs. The call answers a Task
async fun (string p) => DoAsync(p)✅expression body: ONE expression, which may itself be an await (async fun (p) => await DoAsync(p) answers the value). Left unawaited, the body's value IS the inner Task, so an await on the call gives a Task rather than the value
async (string p) => ...❌ Refusedthe async modifier cannot prefix an arrow, because async ( is read as a CALL to a name async: Expect ')' after arguments. (expected 'RightParen', found 'Identifier'). Write async fun (string p) { ... }
async x => x❌ Refusedthe same, without the parentheses: Expect ';' after declaration. (expected 'Semicolon', found 'Arrow')
(string p) => { await DoAsync(p); }❌ At run timea lambda without async is synchronous, so it PARSES and the await is refused when the call runs: await expects a Task (or an awaitable request such as Coroutine.Sleep)
// The arrow takes both bodies; the keyword takes an expression after => or a block in braces var add = (int x, int y) => x + y; print(add(2, 3)); // 5 var join = (string a, string b) => { return a + "|" + b; }; print(join("x", "y")); // x|y var dbl = x => x * 2; print(dbl(21)); // 42 var abs = x => { if (x >= 0) return x; return -x; }; print(abs(-5)); // 5 var answer = () => 42; print(answer()); // 42 var kwExpr = fun (int x) => x * 2; print(kwExpr(21)); // 42 var kwBlock = fun (int x) { return x * 3; }; print(kwBlock(2)); // 6
// An async lambda: the keyword, a brace body, and the await inside it async Task<string> DoAsync(string p) { await Task.Delay(10); return p + "-done"; } var work = async fun (string path, string content) { var r = await DoAsync(path); return r + "|" + content; }; var t = work("alpha", "beta"); print(typeof(t)); // Task print(await t); // alpha-done|beta // The arrow body holds ONE expression, and that expression may itself await var upper = async fun (string p) => (await DoAsync(p)).ToUpper(); print(await upper("gamma")); // GAMMA-DONE
Why the keyword form is the only async lambda. A C# snippet written async (string path, string content) => { ... } does not parse here: the parser meets async ( as a call to a name async, so the modifier cannot begin an arrow. Both async (p) => ... and async p => p are parse errors whose messages name the tokens they found, and the spelling that works in both cases is async fun (p) { ... }. Note also that a plain arrow with a block body is synchronous, so an await inside it is refused at run time rather than at the parse.

Arrow lambda rules:

  • (args) => expr expression body (no fun required)
  • (args) => { ... } block body with =>
  • Bare single parameter: x => expr and x => { ... } (C#-style) the parens are optional when there is exactly one untyped parameter; multiple untyped params still need parens ((x, y) => ...), and typed params keep the paren form ((int x) => ...)
  • Parameters without explicit type default to object?
  • Typed parameters work the same as fun: (int x, int y) => x + y
  • Closures, delegates, and higher-order functions work identically
  • Generic functions still require fun/named function syntax

Generic functions use <T> syntax: T Identity<T>(T x) { return x; }. Type arguments can be inferred from call arguments or specified explicitly: Identity<long>(42). See assets/language/repl/core/generics_showcase.slc for a complete reference.

Generic return types. Generic functions may use T[], List<T> or Dictionary<K, V> and arrays of these, e.g. List<T>[] as their return type (or as a generic collection type anywhere in the signature). Inside a generic function, typeof of such a generic collection reports the concrete instantiation "List<int>", not a bare "List". List<T>.ToArray() and HashSet<T>.ToArray() return a typed T[] (e.g. int[], string[]) never object[], so the elements are not boxed and a generic function returning T[] delivers the concrete array type, which typeof reflects: typeof(evens) is "int[]" for Filter<int>(...).
T[] Filter<T>(Array items, Predicate<T> pred) { var result = new List<T>(); foreach (var i in items) { if (pred(i)) result.Add(i); } return result.ToArray(); } var evens = Filter<int>([1, 2, 3, 4, 5], (x) => x % 2 == 0); print(evens.Length); // 2 Filter<int> returns int[] var collect = Collect<int>([1, 2, 3]); // List<T> Collect<T>(T[] items) { ... } print(typeof(collect)); // "List<int>" the concrete instantiation
Type-argument mismatch warning. A generic type argument that does not match the runtime value produces an early call-site warning (never an exception): Type mismatch: Type argument 'int' for 'T' does not match the runtime type 'string' of argument 1. The call keeps running the coercion still errors (catchably) later if the mismatched value is actually used.
// [WARNING] Type mismatch: Type argument 'int' for 'T' does not match the runtime type 'string' of argument 1. var warned = Filter<int>(["a", "b"], (x) => x == "a"); // warns only no exception // the string→int coercion still throws (catchably) when the value is used inside the function
Bare Identifier => ... in match/switch-expression arms is a PATTERN, not a lambda. Inside subject match { ... } (and switch arms), a bare identifier followed by => is parsed as an arm pattern (Function => "Function" matches a value that is Function, or five => "yes" compares the subject to the constant five) exactly the pre-existing behavior. The bare-lambda form applies only in ordinary expression positions.

Function, Iterable and RandomAccess are usable signature annotation types on parameters and return types, in named functions, fun/arrow lambdas, methods, and local functions. Function is the callable type (lambdas, named functions, bound methods, combined delegates, natives) and can be invoked directly inside the body. See the Internal Types entry for the full contract.

See also assets/language/repl/regression/crash_arrow_lambda_test.slc for a comprehensive test of all patterns.

Closure capture: Closures capture variables (bindings), not value snapshots later assignments are visible inside the closure. Captured locals are RefCell-backed, so the closure and the enclosing scope share the same cell and writes go through on both sides; captured const values stay snapshots. Closures can mutate global variables. Method calls on reference types (like List.Add()) work because the object reference itself is shared. Local functions capture the same way and when they run on the VM their captures are VM-bound (materialized into the VM frame from the same RefCells), so mutation is visible on both sides there too.

// ✅ Closures CAN mutate global variables int result = 0; var fn = () => { result = 42; }; fn(); print(result); // 42 // Also works via method call on shared reference var items = new List<int>(); var fn2 = () => items.Add(7); fn2(); print(items[0]); // 7
Prefer proc.ExitCode after WaitForExit() over the onExited callback the callback runs on a ThreadPool thread and cannot reliably modify script variables. Stdout/stderr callbacks work correctly but still need sleep(300) after WaitForExit() for async draining.
Recursion depth limit: the interpreter runs script calls on a flat heap call stack deep non-tail recursion grows the heap, not the native thread stack, so legitimate recursion can go very deep (sumTo(5000), sumTo(100000) all run fine the cap is 1000000 nested VM calls under NativeAOT (30000 in Debug/JIT), bounded by memory, and it works even in JIT builds where the old re-entrant path overflowed at ~2000). A true runaway (e.g. int boom(int n) { return boom(n + 1) * 2; }) throws a catchable ScriptException (Maximum call depth exceeded (1000000) possible runaway recursion. under NativeAOT) it never crashes the process, and the guard is silent (no console warning). Tail-recursive calls are optimized into a loop and run in constant stack (tailRec(100000, 0) runs in constant stack; the 1000000-iteration tail-loop guard bounds an infinite tail loop, and SLC_VM_MAXFRAMES lowers it). Functions that fall back to the tree-walker (coroutines, unsupported constructs, or after VmSetEnabled(false)) are still bounded by the interpreter guard (3000 under NativeAOT, 24 in Debug/JIT see the VmSetEnabled entry for the full table), and the AOT build keeps a 32 MB process stack as a safety net.

Recursive lambdas two-step binding

A lambda that calls itself needs its own name, but the var binding does not exist until its initializer has finished evaluating. Declare the binding first, then assign the lambda:

// Two-step pattern binding first, lambda second (verified: prints 4181; VM and tree paths identical) var fibPair; // binding first fibPair = ((int n)) => { if (n <= 1) return (n, 1); var prev = fibPair(n - 1); // closure sees the late assignment return (prev[1], prev[0] + prev[1]); }; print(fibPair(19)[0]); // 4181

The one-liner does not work:

var fib = ((int n)) => { /* ... fib(n - 1) ... */ }; // invoking it raises Undefined variable 'fib'

The lambda is evaluated before fib exists the closure snapshot is taken at creation time, so there is no capture for fib to resolve against. The initializer itself completes, but the first call raises Undefined variable 'fib' (cleanly, on both the VM and tree paths never a VmFallback leak and never a crash). The two-step form works because the binding exists in scope when the closure is created: closures capture the variable (binding), so the later assignment is visible.

Design note: JS-style hoisting (auto-defining the declaration name before evaluating its initializer, so the one-liner would work) was considered and deliberately rejected it would change the semantics of every var x = init (var x = x; self-assignments, order surprises). The engine keeps its C#-flavored var semantics.

Alternative: a local named function can also recurse local functions run on the VM exactly like top-level functions. A local function is lazily compiled to bytecode on its first invocation, and its recursion is VM-flat: it grows the VM's flat heap frame list, not the C# call stack. Deep local recursion is therefore no longer capped by the Debug tree-walker (MaxCallDepth 24 in JIT builds) the bound is now the VM's frame cap (VmMaxFrames: 30000 in Debug/JIT, 1000000 under NativeAOT). Verified against the Debug exe: var Deep(int n) { if (n <= 1) return 1; return n + Deep(n - 1); } recursing to Deep(1000) returns 500500.

A local function is in scope for the whole body it is declared in, as in C#, so a closure written above it can still call it. The name is bound when the body starts and the declaration fills it, so the closure sees the function when it runs. This is the shape a callback written before its helper has, and it works at the top level, inside a function, inside an if and inside a loop:

// The handler is written ABOVE the function it calls, and both work var hits = [].ToList(); var handler = fun (string s) { Note(s); }; // created before Note exists var label = "late"; // declared between them, and Note still sees it void Note(string s) { hits.Add(label + ":" + s); } handler("one"); print(hits[0]); // late:one

One limit comes with it: calling a local function before its declaration runs is refused, naming it (The function 'Note' is used before the declaration that defines it in this block ...), because the function itself is created when the declaration executes. Order therefore matters for the CALL, never for a name a closure captured. The shape runs on the bytecode VM like any other body: the slot exists from the start of the block, a closure created above the declaration captures it as a cell, and the declaration fills that cell (measured on a 2,000-call loop through such a handler: VM: 4001 (100.0%) | Tree: 0).

The two-step pattern also works nested inside a function closures capture variables (bindings), so the closure created inside the function sees the later assignment to fibPair and recurses through the same RefCell. Verified against the Debug exe (prints 4181; VM and tree paths identical):

// Nested two-step pattern binding first, lambda second (verified: prints 4181; VM and tree paths identical) var NestedFib() { // local function (untyped) Function is a return-type keyword var fibPair; // binding first fibPair = ((int n)) => { if (n <= 1) return (n, 1); var prev = fibPair(n - 1); // the captured binding is live recursion works return (prev[1], prev[0] + prev[1]); }; return fibPair(19); } print(NestedFib()[0]); // 4181
// Deep local recursion the named-function alternative runs VM-flat (verified against the Debug exe: prints 500500) var Host() { var Deep(int n) { if (n <= 1) return 1; return n + Deep(n - 1); } return Deep(1000); } print(Host()); // 500500 (previously: Maximum call depth exceeded (24) on the Debug tree path)
// Delegate-typed lambda parameters Action / Func<,> / Predicate<T> work in both lambda forms var run = fun (Action a, Func<int, int> g) { a(); return g(21); }; print(run(fun () { }, fun (int x) { return x * 2; })); // 42 // Arrow form same delegate-typed params var arrowRun = (Action a, Func<int, int> g) => g(21); print(arrowRun(fun () { }, fun (int x) { return x * 2; })); // 42 // Predicate<T> param too var isBig = fun (Predicate<int> p) { return p(5); }; print(isBig(fun (int x) { return x > 3; })); // True
named arguments Pass arguments by name f(x: 1, y: 2) order-independent

Arguments can be passed by name using name: value syntax. Named arguments are reordered to match the callee's parameter list at the call site, so they can appear in any order and be mixed with positional arguments (positional must come first, like C#).

f(x: 1, y: 2); obj.Method(name: "a", count: 3); new Person(name: "Alice", age: 30);
void draw(int x, int y, string label) { /* ... */ } draw(x: 10, y: 20, label: "origin"); draw(label: "pt", y: 5, x: 1); // any order draw(0, label: "zero", y: 0); // mixed: positional first
Named arguments work on script functions, methods, and constructors. Calls using named arguments are compiled to the bytecode VM: the compiler emits the arguments in source order plus a name-mapping const, and the VM reorders them against the callee's parameter list before binding. Named arguments on a local/parameter callee (e.g. a lambda stored in a local variable) still fall back to the tree interpreter.
On an overloaded name, the NAMES choose the member: with Nm(int a, string b) and Nm(string a, int b), Nm(b: 1, a: "s") is the second one, because each candidate is asked whether its parameter list has those names (C#'s rule), and the call is then bound through that same mapping. A name no parameter has, and the same name twice, are refused as such Named argument 'c' does not match any parameter., Named argument 'a' specified more than once. rather than as an arity problem.
local functions Nested named functions declared inside a method/function body

A function declared inside another function's body is a local function. It is scoped to the enclosing block, can capture and mutate the enclosing locals, and supports all normal function forms (typed, void, var, expression body, tuple return).

Two declarations of one name with DIFFERENT parameter lists are an overload set, exactly as for a top-level function (see Function): each call resolves by argument count and type, the exact type beating a widening one, and a tie going to the first declaration.

int outer(int n) { int double_(int x) { return x * 2; } return double_(n) + 1; }
// Capture + mutate an enclosing local int counter() { var acc = 0; int add(int x) { acc = acc + x; return acc; } add(3); add(4); return acc; // 7 } // void and var forms int useVoid() { var total = 0; void bump(int v) { total = total + v; } bump(5); return total; // 5 } // Tuple-returning local function inside a lambda var outer = fun (int v) { (int a, int b) mid(int w) { return (w + 1, w + 2); } return mid(v); };
Local functions are not visible outside the enclosing body. They reuse the lambda closure machinery mutable captures are promoted to RefCell so writes propagate back to the enclosing scope. Local functions run on the bytecode VM like top-level functions (lazily compiled on first invocation), with their captures VM-bound: the same RefCells are materialized into the VM frame, so mutation is visible on both sides and recursion stays VM-flat.
pure Pure function results are memoized

Pure functions must be deterministic same inputs always produce the same output. Results are cached in _pureMemoCache.

pure int square(int x) { return x * x; }
pure int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } print(fib(10)); // Result: 55 (memoized)
Memoization is keyed by the function name + argument values. Cache can be cleared with ClearPureCache().
yield Suspend a coroutine and produce a value direct call returns a Generator (MoveNext / Current / foreach)

Functions containing yield are auto-detected as coroutines. Call the function directly to get a Generator a lazy iterable driven with MoveNext()/Current or consumed with foreach or pass it to Coroutine.Start() to run it as a background coroutine. Generator arguments are preserved: the first MoveNext() runs to the first yield with the original arguments in place.

What a coroutine is

  • Cooperative multitasking on one thread many logical executions interleaved at explicit yield points, no OS-thread overhead.
  • Stateful, resumable, controllable the status lifecycle (NotStarted/Suspended/Waiting/Completed/Dead), Continue()/Abort()/Reset() actions, LastYieldedValue (the last yielded value after completion it keeps that last yield and is what an iterator's Current reads; the body's return value is Coroutine.ReturnValue, null until it completes naturally), per-coroutine memory.
  • Await-style requests yield Coroutine.Sleep(ms) / Wait(evt) are deferred: the coroutine expresses "don't resume me until X," and the driver (the Pump() loop) enforces it. This is the one green-thread-like trait: the coroutine can suspend for a reason rather than a fixed number of steps. Coroutine.Pump() drives the interpreter of the RUN that calls it, so a pumping loop behaves the same in an embedded session (ScriptLangCore.Launcher.exe) as from the command line.
yield value;
// As a coroutine (background execution) int countTo(int max) { var i = 0; while (i < max) { yield i; i = i + 1; } return i; } var co = Coroutine.Start(countTo, 3); // auto-starts the first yield (0) is consumed inside Start print(co.Resume()); // Result: 1 print(co.Resume()); // Result: 2 print(co.Resume()); // Result: 3 // As a Generator direct call, explicit MoveNext()/Current (no thread, no pump) print(typeof(countTo(3))); // Result: "Generator" the name a script can also write: `gen is Generator` var gen = countTo(2); // nothing runs until the first MoveNext() print(gen.MoveNext()); // Result: True runs to the first yield print(gen.Current); // Result: 0 argument 2 reached the body (preserved on first resume) print(gen.MoveNext()); // Result: True print(gen.Current); // Result: 1 print(gen.MoveNext()); // Result: False the function returned, enumeration is over // The same Generator, consumed by foreach foreach (var n in countTo(3)) { print(n); // 0, 1, 2 } // Nested generators a coroutine may call another coroutine by bare name int pairs(int n) { var i = 0; while (i < n) { yield (i, i * 2); i = i + 1; } return -1; } int nested(int n) { foreach (var v in pairs(n)) { yield v; } return -1; } foreach (var t in nested(2)) { print(t[0], t[1]); } // 0 0, 1 2 generator loop frames stay isolated

The yielded sequence vs. the return value

A generator produces two distinct things: the yielded sequence exactly the yield values, which foreach/MoveNext iterate and the return value, which terminates the sequence and is never an element. The return is not mandatory at runtime on the VM path: falling off the end of the body simply ends the generator (after death Current shows null instead of a stored value). It is required on the tree-walker path (VmSetEnabled(false)), which raises Coroutine 'X' must return a value. for a body that ends without one and it is the honest type-contract for a function declared int. return -1; is the conventional sentinel used in these examples: it satisfies both paths and closes the sequence without contributing a value to the consumers.

// foreach sees ONLY the yields the return value is never an element int gen() { yield 1; yield 2; return -1; // terminates the sequence NOT an element } var s = ""; foreach (var x in gen()) { s = s + x + ","; } print(s); // "1,2," // MoveNext step by step the return value only appears once the generator is done. // g.Status tracks the lifecycle: NotStarted → Suspended (while iterating) → Completed (natural end). var g = gen(); print(g.Status); // NotStarted print(g.MoveNext(), g.Current, g.Status); // True 1 Suspended print(g.MoveNext(), g.Current, g.Status); // True 2 Suspended print(g.MoveNext(), g.Current, g.Status); // False -1 Completed ran to its return naturally print(g.Status == CoroutineStatus.Completed); // True (naturally exhausted) // Action vocabulary Continue()/Abort()/Reset() complete MoveNext()/Dispose(). // A break-abandoned generator is Suspended, NOT stuck: Continue() resumes it. int gen2() { yield 1; yield 2; return 0; } var g2 = gen2(); foreach (var x in g2) { break; } // abandoned → Suspended (yield 1 consumed) print(g2.Continue(), g2.Current); // True 2 resumed from the yield point print(g2.Continue(), g2.Status); // False Completed ran to its return var g3 = gen2(); foreach (var x in g3) { break; } g3.Abort(); // ≡ Dispose → Dead, state freed print(g3.Status); // Dead var g4 = gen2(); g4.MoveNext(); g4.Reset(); // safe destroy → Dead, no exception print(g4.Status, g4.MoveNext()); // Dead False
Read Current only while MoveNext() returned True. After the generator returns, MoveNext() stays False forever; the return value is the coroutine's completion result (stored as LastYieldedValue / returned by the final Resume()), but the foreach/MoveNext contract is defined over the yielded values only. To check where a generator is in its lifecycle, read g.Status: NotStarted before the first MoveNext, Suspended/Waiting while iterating, and once exhausted Completed if it ran to its end naturally or Dead if it was disposed/abandoned (e.g. g.Status == CoroutineStatus.Completed); the raw Coroutine is also reachable via g.InnerCoroutine. Action vocabulary: g.Continue() ≡ MoveNext() (resumes an abandoned break generator from its yield point), g.Abort() ≡ Dispose() (→ Dead, state freed), g.Reset() = safe destroy (→ Dead, no exception generators are one-shot, so re-create for a fresh run).
VM-safety gate gap the loud fallback: a generator body is compiled to VM bytecode when the compiler's analysis considers it VM-safe. That analysis is conservative but not exhaustive, so a body may still contain a construct the VM cannot execute e.g. delegate subtraction f - g, which is not a defined operation on any path (the tree raises Cannot convert 'func …' to number; only f + g combines delegates). When the VM meets such a construct at runtime it falls back loudly instead of silently re-running the body: before the first yield it throws a catchable VM generator 'X' cannot execute its body on the bytecode VM … (possible VM gate gap; the generator stayed VM-backed because its body appeared VM-safe), and after a yield it throws VM generator 'X' cannot be resumed after the bytecode VM fell back (…). Side effects executed before the failure run exactly once the fallback never double-executes the body. The same construct on the tree path (VmSetEnabled(false)) produces the standard runtime error.
async / await Suspend an async function on a Task without blocking a thread: a call returns a Task

async marks a function whose body may await. Calling one returns the Task this engine already had: the body starts, runs to its first suspension, and the caller holds a task that completes with the body's return value, or faults with whatever the body threw. Nothing blocks a thread while the body waits, and that suspension belongs to the runtime rather than to a compiler-generated state machine: the engine builds against .NET 11 with <Features>runtime-async=on</Features>, and Task.Delay is an async engine method.

A .NET task is awaited the same way: a member taken from the CLR surface of a namespaced facade (see File) hands the script this engine's own Task, so var text = await File.ReadAllTextAsync("./report.txt"); reads a file without blocking a thread, and a failure travels as the engine's mapped refusal rather than an AggregateException.

async Task<Type> Name(params) { await expr; ... } // or, with an expression body async Task<Type> Name(params) => await expr;

Declaring an async function

FormSpellingNotes
typed functionasync Task<int> Fetch(int ms) { ... }the return value becomes the task's result
no resultasync Task Log(string s) { ... }no result, and the call still hands back a Task
expression bodyasync Task<int> Answer() => 42;await may sit in the expression
local functionasync Task<int> Local(int v) { ... }the same forms, declared inside another body
modifier orderpure async Task<int> F() { ... }async comes after the other modifiers, as in C#
async Task<int> Fetch(int ms) { await Task.Delay(ms); // suspend here, no thread is held return ms; // becomes the Task's result } async Task Log(string text) { await Task.Delay(1); print(text); } async Task<int> Answer() => 42; // expression body, no await needed async Task<int> Sum(int ms) => await Task.Delay(ms) + 1; // await inside an expression body void Outer() { async Task<int> Local(int v) { // a local async function await Task.Delay(0); return v * 3; } print(Local(7).Result); // 21 }

What can be awaited

  • the Task another async call returned, which is what lets async bodies compose;
  • Task.Delay(ms), the delay that holds no thread, and Task.Delay(ms, token), which faults the task instead of completing it when the token fires;
  • a Task that is already complete, including Task.CompletedTask, which costs no suspension at all;
  • Task.Yield(), the yield point C# has: incomplete when it is read, so the body really hands control back and resumes on a later pass of the run queue, with null as its value;
  • the awaitable requests the coroutine machinery already had, the same set yield accepts: Coroutine.Sleep(ms), Coroutine.Wait(evt), Coroutine.Fetch(url), ReadLineAsync().

Statements that take await

Two STATEMENTS are awaited, and both spellings are C#'s: await foreach reads an IAsyncEnumerable<T> one MoveNextAsync at a time and disposes the enumerator on every exit (the foreach entry has the detail), and await using awaits an IAsyncDisposable's disposal (the using entry does). Neither compiles to bytecode, so a source-less bundle carries such a file's source instead of stripping it.

await foreach (var line in File.ReadLinesAsync('data.csv')) { print(line); } await using (var seq = File.ReadLinesAsync('data.csv')) { // DisposeAsync awaited when the block exits, even on an exception }

An await keeps a window alive

An awaiting script's window stays live: the pump a suspension is driven from also dispatches the queued messages, so a pending repaint is delivered and a queued click runs its handler during the wait. That is C#'s own behaviour on a UI thread, where a continuation is resumed through the message loop, and it is what makes await usable in a tool that owns a form. The boundary is deliberate: sleep dispatches nothing, so a handler never re-enters a statement that is merely blocking, while every other pump caller (an await, Task.Wait(), .Result, a coroutine sleep, Application.DoEvents()) is a wait that already gives the window a slice. Pinned by await_window_liveness_test.

async Task Work() { await Task.Delay(700); // the form keeps painting and taking clicks through this } Work().Wait();

An async Task body may fall off its end, exactly as a bare return; does, so a body whose last statement is a call, an await or an await foreach needs no closing return. An async Task<T> body owes a value on every path, which is C#'s own rule, and the refusal says so.

async Task<int> Twice(int ms) { var a = await Fetch(ms); // await another async call var b = await Fetch(ms); // then a second one, sequentially return a + b; } async Task<string> Sleepy() { await Coroutine.Sleep(10); // the awaitables yield already accepted are awaitable return "woke"; } async Task<int> Quick() { var done = Task.Delay(0); print(done.IsCompleted); // True return await done + 3; // already complete: the await does not suspend } async Task<int> Total() { var a = await Task.Delay(1); // one await per top-level statement var b = await Task.Delay(2); var c = await Task.Delay(3); return a + b + c; // 6 }

Async members and lambdas

A method carries the modifier the way a function does, and the receiver travels with the body, so this reads the instance. An async fun lambda is a value like any other lambda, and calling it returns the Task. Task.CompletedTask is a Task that is already complete, which an await takes without suspending.

class Loader { public int Base = 40; public async Task<int> Grow(int by) { await Task.Delay(1); return this.Base + by; // the receiver is bound } } print(new Loader().Grow(2).Result); // 42 var f = async fun(int n) { await Task.Delay(1); return n * 2; }; print(f(4).Result); // 8 async Task<int> Work() { await Task.CompletedTask; return 42; } // no suspension at all print(Task.Run(Work).Result); // 42 an awaited method handed to Task.Run is unwrapped

Where an await may sit

An await belongs in the body, and any of the ordinary statements can hold it: the top level, an if, a try, a plain block, or a while, a for and a foreach body, as a statement, as the value of an expression (t = t + await f()), or bound to a local. A local bound from the awaited value survives, a loop body keeps the element or the index its iteration is on, and a fault raised there is caught by the enclosing try. A file's TOP LEVEL is where a script's own await belongs, as C#'s async Main is for a program: it may await, and it may just as well run ordinary code (see the file's top level as an async entry below).

await f(); // statement var r = await f(); // bound to a variable return await f(); // the awaited value as the return value

A file's top level as an async entry

Running a file is asynchronous, so a file-level await suspends the run instead of parking the calling thread: the awaited task's completion resumes the same statement, and a host keeps control in between (its own message loop, slc_poll, slc_cancel). A run whose statement is re-entered that way continues with the value the await answered, so an operand is awaited once and a fault is raised at that await's own position, inside the statement, where the script's own try catches it.

Several awaits in one statement are fine, which covers the shapes an expression naturally produces: var total = (await a()) + (await b()); awaits both, in the order the expression evaluates its operands. A branch that is not taken is not awaited, and the values answer in reach order whatever the tasks' durations are. The parentheses in that line are for the reader rather than for the grammar, because an await takes one postfix chain as its operand and the + already sits outside both: the table below says which positions need them and why.

async Task<int> Part(int n) { await Task.Delay(50); return n; } // a file's top level: two awaits in ONE statement, each answered once var total = (await Part(4)) + (await Part(4)); print(total); // 8

Where parentheses around an await are needed

An await takes ONE operand, and that operand is a postfix chain: a name, a call, a member or an index, with anything chained onto it. Everything else binds outside the await, in the order the language already gives it, so a parenthesis is needed exactly when the awaited thing has to be more than one chain, or when the awaited VALUE has to be read further.

shapeparentheseswhy
(await a()) + (await b())optionalEach await's operand is one call, so the + already sits outside both: await a() + await b() is the same expression, and so is a comparison, a ?? or a * in that place. The parentheses are a reading aid, which is why the examples here keep them.
await (a() + b()), await (flag ? x() : y())requiredTo await a WHOLE expression the parentheses are the operand: without them await a() + b() is (await a()) + b() and await flag ? x() : y() is (await flag) ? x() : y(), which awaits the CONDITION and then hands the chosen branch's Task back unawaited (its typeof is Task). What is inside must then be a value: await (a() + b()) over two async calls is refused, because two Tasks cannot be added.
(await t).Proprequired, for a member of the awaited valueThe await's operand is the whole chain, so await t.Prop awaits the Task that Prop returns. To read a member of the VALUE the task carries, the parentheses make the operand the task itself: await t.Prop on a Task<Box> answers Property 'V' not found on type Task, and (await t).Prop answers the member.
a branch of a ternary: flag ? await x() : ynot neededA branch is already an expression position, so an await is legal there as written, on either side of the :.
a value position: x = await f(), return await f(), f(await a(), await b()), [await a(), await b()], $"{await f()}"not neededEach of those positions takes a whole expression, so the await is one: what binds outside it is that position's own operator (the =, the comma of an argument list, the hole of an interpolation).
!await f(), -await f(), (long)await f(), await await tnot neededA unary operator, a cast and a second await each take an expression in their own position, so await await t reads the first await's value as the second one's operand, exactly as await (await t) does.
$"{(flag ? a() : b())}"required, and not for the awaitA hole splits on : for a format specifier, so a TERNARY inside one needs its own parentheses whether an await is involved or not. $"{await f()}" needs none.
await foreach (var x in seq), await using (var r = init)the parentheses belong to the statementBoth are statement forms rather than expressions, so there is no awaited operand to parenthesise: the parentheses hold the loop head or the resource, as their headings in the foreach and using entries show.

Some places keep the waiting rule instead, and each one is a place where re-entering the statement would change the answer. An await either suspends, the run hands control back and the same statement resumes with the value, or waits on the spot, where a thread inside the engine waits, driving the pump, until the awaited call finishes. The value is the same either way, so the split does not show in a result; the table is the whole of it.

await t at a file's top level, on its own, outside a loopsuspendsResuming is indistinguishable from re-entering the statement, so the run gives control back: a host's message loop, slc_poll and slc_cancel stay live while the script waits.
await t inside an if, a try or a plain blockwaitThe sub-statement's earlier statements would run a second time.
await t in a while, a for or a foreach bodywait, once per roundA replay would replay the rounds already done and an accumulation would count them twice (a two-round loop that owes 12 answered 24).
await foreach, per elementwaitA replay would re-open the enumerator, and the elements already read would be read again.
the disposal of an await usingwaitIt runs in a finally, and a replay would build the resource again before disposing it.
an asynchronous sequence as the source of http.StreamLines / StreamEvents, per elementwaitThe producer is pulled on the request thread, and a stream source is a synchronous contract by design.
any of the above inside a nested run (RunScript, a module body)waitA nested run has no driver of its own to resume it, so its awaits wait whatever shape they have.

A loop that must suspend belongs in an async function, whose body resumes at the statement inside the loop; the same advice covers the branch and the block.

The waits are counted and cancellable, which is what makes them safe to leave in place. Diagnostics.AsyncParks() totals them and Diagnostics.AsyncParks("await foreach") asks about one shape (the sites are await, await foreach, await using, http stream and Task.Wait), so a suite can assert that a shape waits rather than suspends without a clock; Diagnostics.Trace("ASYNC_TRACE", true) (or SLC_ASYNC_TRACE=1) prints one line per wait with its site and how long it lasted. And a run's own token reaches them: slc_cancel or cts.Cancel() wakes such a wait instead of being noticed only when the awaited call returns, raising the engine's Cancelled at the awaiting statement's position. A 900 ms awaited delay whose cancel is issued at 80 ms therefore ends the run in about 110 ms rather than waiting out the remaining 820.

var sum = 0; for (var i = 0; i < 3; i = i + 1) { sum = sum + await Part(4); // waits on the spot, once per round } print(sum); // 12

Work written before an await in the same statement happens once. A suspended statement is re-entered rather than split, so the engine remembers the values that statement had already computed and answers them again on the re-entry: Step("a") + (await Part(4)) + Step("b") calls Step once for each argument, not once per resume, which is the single evaluation C# gives you. What still runs again is work written BETWEEN two awaits of one statement, because only the prefix up to the first suspension is remembered; bind the second awaited value in its own statement when that work must happen once. A body the compiler declines (one holding an is pattern, a using body or a nested function) runs on the tree, where a second await in one statement is refused by name instead ("'await' can be used once per statement"); its advice is the same one, bind each awaited value in its own statement.

Differences worth knowing

For the ordinary shapes this is real async/await, with C#'s syntax and C#'s semantics: the operator, the types, Task.Run, WhenAll and WhenAny, await foreach and await using, async lambdas, a fault raised into the script's own try, resumption on the thread the run is on, and top-level await. What follows is every place the answer differs, each row measured on this build rather than inferred from C#. The state of the art is the whole table: a row that is not here is a row that behaves as C# does.

differencemeasured behaviour
no async voidrefused by name: this engine has no unawaitable `async void`: an async body always hands back a Task here, so write `async Task`, with C#'s own reason for the keyword (async void is for event handlers). An async lambda handed to an Action is accepted and runs fire-and-forget, which is the shape C# would give it
no custom awaitablesthe GetAwaiter duck typing C# allows is refused: await expects a Task (or an awaitable request such as Coroutine.Sleep). A class of your own with a GetAwaiter is not awaitable here
no Task.Wait(int), no Task.Wait(token)Method 'Wait' not found on type Task with 1 argument(s), so a timed wait has to be spelled with a Task.Delay and WhenAny. Wait() itself is there, and what a negative timeout would mean is a decision this engine has not taken rather than one it took differently
no async iteratorsasync meeting yield is refused with the sentence C# uses for the return type: an `async` body must declare a `Task`, a `Task<T>` or `void`, as C# requires (CS1983). A script consumes asynchronous sequences with await foreach but cannot produce one that way (Events.Create is the producer), and async Task Gen() { yield return 1; } is refused at the parse, because a Task body holds no elements to yield
ConfigureAwait(bool) is a no-opaccepted so ported code reads unchanged, and it answers the SAME task: there is no synchronisation context to leave, because every continuation is posted to the run's own queue whatever the flag says
Task.Yield() is an engine Task, not a YieldAwaitablethe shape a script writes is C#'s and the effect is C#'s: the task is incomplete when it is read, so the caller really continues first (measured ["caller", "body"]), the body resumes on a later pass of the run queue, and the value a yield answers is null. Because the type is the engine's Task, var v = await Task.Yield(); reads null here where C# refuses the shape at compile time (its GetResult is void), and Task.Yield().Wait() is legal here and would not be there
a fault is an engine refusal, not a CLR exceptionawait Boom() inside a try raises the awaited body's own fault with its position, Division by zero (at line 21, column 47), and the script's catch sees it. A Task.WhenAll over two faults names BOTH in one line, Multiple failures: 'Division by zero; second', where C# surfaces the first one and buries the rest in the aggregate
cancellation reads as the engine's own sentenceTask.Delay(ms, token) faults the task when the token fires, with the awaited operation was cancelled before it completed, which is an engine message rather than a localized runtime one. ThrowIfCancellationRequested is the exception to that rule: it surfaces the CLR's own OperationCanceledException under a [ThrowIfCancellationRequested] key, resource text included
a file's top level: a LOOP parks a threada lone top-level await suspends the run and parks nothing, and the same loop of awaits inside an async function parks nothing either (both measured at 0 through Diagnostics.AsyncParks()); the loop at the TOP LEVEL parks once per round (2 for 2 rounds), because a replay there would replay the rounds. Put the loop in an async function when the host has to stay live
several awaits in one statement, in a body the compiler DECLINESan async body compiles, and a file's top level keeps an await journal, so both await every operand of the statement; a body the compiler declines runs on the tree, where the second await is refused by name ('await' can be used once per statement) with the fix in the message, var x = await a; var y = await b;. The refusal is the safe half: the shape cannot silently answer wrong
work AHEAD of an await in a tree-walked body, and BETWEEN two awaits anywherethe value is always right, and two side effects are not: a callee doing a member call ahead of the await in a declined body runs on every pass, so S("a") + (await FW(1)) answered A1 while the log held a,a, and work written between two awaits of one statement runs once per pass, so S("a") + (await W(1)) + S("b") + (await W(2)) + S("c") logged abbc (the answer a1b2c was right). Bind each awaited value in its own statement when the work between them must happen once, which is the same advice as above

Pointers, refs and unsafe code

A suspension here holds nothing in a register: the engine records the body's position and its locals and resumes the body in the same process, and one cooperative pump drives every body on the same thread. So a raw pointer or a native handle you hold across an await is still usable afterwards, and a local of any type survives the suspension. That is a deliberate difference from C#, where the state of a suspended method lives in a heap object, the scheduler may run the continuation on another thread, and a pointer across an await therefore needs pinning.

C# refuses two shapes across an await, and both are about a suspension moving the state to the heap or resuming it on another thread: a fixed pointer (the compiler reports "cannot await in context of a 'fixed' statement") and a by-ref local ("a ref local cannot be kept across an await or yield boundary"). Everything else around unsafe code is ordinary there too: a stackalloc buffer, an address taken from a local, and an unsafe block are all accepted in an async body, and an await may sit in a try, a catch and a finally alike. Here none of the two applies, because nothing is pinned and no local moves, so the body you write is the body that runs: a pointer from Mem or a native library is safe to carry across an await, and a by-ref parameter stays live across one.

The Task you get back

An async call hands back the ordinary Task, so its whole surface applies unchanged. The wait members drive the coroutine pump for you, which is what lets a task reach completion without the script having to pump anything itself.

MemberOn a Task an async call returned
.Status"Running" while the body is suspended, then "Completed" or "Faulted"
.Wait()drives the pump until the body finishes; rethrows a fault
.Resultthe body's return value; drives the pump, and throws if the body faulted
Task.WhenAll(list)accepts these Tasks, and the composite is driven by waiting on it
.ContinueWith(fn)runs fn on the main thread once the body completes, chained arbitrarily
Task.Run(fn)accepts an async function, and the task is UNWRAPPED as in C#, so it carries the async body's value instead of a nested Task. A WORK function runs on the interpreter the script is running on, so its body reads and writes the same globals the calling code does, including inside a nested RunScript. Given a token (Task.Run(fn, cts.Token)), that token is the body's KILL SIGNAL while it runs, and a pre-cancelled one means the body never starts
awaitthe awaited value of the body, which is how one async body waits for another

Inside an async body, await the task: that is the spelling to prefer, and it is how one async body waits for another. At a file's top level the two are equivalent, because a top-level await waits on the spot, so await reads the same there and is the spelling to reach for: .Result and .Wait() stay available, and are the tools to pick when you want the wait to be visible in the code or when you are in a body that cannot await.

var t = Fetch(30); print(t.Status); // Running t.Wait(); // drives the body to completion print(t.Status); // Completed print(t.Result); // 30 // Task.Run accepts an awaited method: C# unwraps it, so the task carries the VALUE async Task<int> Load() { await Task.Delay(5); return 7; } var loaded = Task.Run(Load); print(loaded.Result); // 7, not a Task async Task<int> Plus1() => await Task.Run(Load) + 1; // 8 the unwrapped value, awaited var a = Fetch(10); var b = Fetch(15); Task.WhenAll([a, b]).Wait(); // the composite drives its constituents print(a.Result + " " + b.Result); // 10 15 var seen = 0; var c = Fetch(5); c.ContinueWith(fun(t) { seen = t.Result * 4; return null; }); c.Wait(); // completes the body and queues the continuation print(seen); // 20

Faults

A throw with no enclosing try in the body faults the Task instead of unwinding the caller, which is C#'s rule. The fault then surfaces wherever the caller touches the task.

async Task<int> Fails() { await Task.Delay(1); throw "boom"; } var bad = Fails(); // the call itself does not throw try { print(bad.Result); } catch (var ex) { print(ex.Message); } // boom print(bad.Status); // Faulted async Task<string> Handled() { // a fault awaited at the body's top level travels on var t = Fails(); var r = await t; return "unreachable"; } try { print(Handled().Result); } catch (var ex) { print(ex.Message); } // boom

Contextual keywords

Both words are contextual, exactly as in C#: inside an async body and at a file's top level await is the operator (at the top level a following operand decides, so print(await) keeps its name), and inside any other body it is an ordinary identifier, so a script may still call a variable await. A function that is not declared async cannot use the operator, and that refusal names the fix.

var await = "a legal name"; // outside an async body this is just an identifier print(await); // a legal name async Task<int> Ok() { return await Task.Delay(1); } int NotAsync() { return await Task.Delay(1); // Error: 'await' is only the await operator, and only inside an `async` function }

Coming from C#

The habits that carry over, and the places where this engine answers differently.

C# habitHere
await the taskthe same, and the spelling to prefer inside a body
.Result / .Wait()work, and they block while they drive the body, which is why C# discourages them. They are for a script's top level, where no body can await; inside a body use await
Task.Run(...), named by WHAT it wrapsan ASYNC method wrapped this way adds nothing, since an async body already waits without holding a thread, so await Load() directly. A BLOCKING call is what it is for, and this engine's File members are all synchronous (and its own refusal lists what it holds: no File.WriteAllTextAsync among them), so await Task.Run(() => { File.WriteAllText(path, text); }); is the right spelling for one
async void, only for an event handlerREFUSED here: this engine has one untyped Task, and an async call always hands back an awaitable Task, so C#'s unawaitable form cannot be expressed. Write async Task
fire-and-forget, _ = F();the Task holds the fault, so a failure is visible only if something reads that task. Await it, or read .Result inside a try
start the independent work, then Task.WhenAllthe same, and it is how several waits run together. A foreach of awaits serialises them, and does not deliver its values anyway, see below
Task.CompletedTask, Task.FromResultCompletedTask is a Task that is already complete, and FromResult makes one that carries a value, so a caller can await it or read it without waiting for anything
ConfigureAwait(false)accepted as a NO-OP that answers the same task, so ported code reads unchanged. The engine owns one cooperative pump and has no synchronisation context to marshal away from
Task<T>, ValueTask, await foreachabsent. The engine's Task is untyped, and .Result or await carries the value

Supported, and not yet

The boundary is written down rather than left to be discovered, and assets/language/probes/probe-async-await.slc runs every shape below and reports a verdict per check, so a row and its instrument can be read together.

CapabilityNowNotes
async on a top-level, local, class or struct function or method✅ Yesa call returns a Task. On a member the receiver is bound, so the body reads this
async on an extension member✅ Yesthe same wrap. A NAMED receiver block (extension(string s)) does not expose its alias inside the body, which the coroutine form of the same member shares
async fun lambdas✅ Yesasync fun(...) { ... } and async fun(...) => expr, where the expression may itself be an await (async fun (p) => await Load(p) answers the value); braces are what hold more than one statement. The bare async x => x and async (x) => ... forms are not accepted at all, since async ( reads as a call: write async fun (x) { ... }. The lambda spelling matrix lists every case
await a Task from another async call, or Task.Delay✅ Yesone body may await another, to any depth
await an already-completed Task, or an existing awaitable request✅ Yesa completed Task does not suspend at all
await at the body's top level (statement, variable, or returned value)✅ Yesthe placement the resume understands
the Task surface on the returned Task: .Status, .Result, .Wait(), WhenAll, ContinueWith✅ Yeswaiting on a task also drives its body
a fault faulting the returned Task✅ Yessurfaces at .Result, .Wait(), or an await at the body's top level
Task.WhenAll over failing constituents✅ Yesthe composite carries the fault, and it names every failure in one line (Multiple failures) through .Wait(), .Result and await alike. One failure stays the plain exception a single task throws, and a composite of successes completes as before
await/async as contextual keywords✅ Yesno existing script is affected by the two names
await inside an if, a try, or a plain block✅ Yesthe value is delivered, a block-local bound from it survives, return await in a branch returns it, and a fault raised there is caught by the enclosing try
await inside a while or a for body✅ Yesas a statement, as the value of an expression (t = t + await f()), or bound to a local in the body, to any nesting
await inside a foreach body✅ Yesthe element stays the one the iteration is on, so t = t + await f(n) accumulates every element
catching a fault that a suspension raises inside a try in the body✅ Yesthe catch sees the awaited task's fault, which is C#'s rule
async on an interface member❌ Not yetrefused by name: an abstract member has no body to suspend in. A class or a struct method is the place for it
Task.CompletedTask✅ Yesa Task that is already complete, and a fresh one per read
Task.Yield()✅ Yesthe yield point, registered through the async door: the task is incomplete when it is read, so the caller continues first and the body resumes on a later pass of the run queue, and the value it answers is null. The type is this engine's Task rather than C#'s YieldAwaitable, see the differences table below
pure on an async function❌ Refusedby name: the memo cache holds a return value, and an async call returns a Task. Drop one of the two modifiers
Task.Run(anAsyncFunction), including from a body evaluated by RunScript✅ Yesthe body starts on the interpreter that is RUNNING the script, so the pump that drives it and the pump its caller waits in are the same one
cancellation: an optional CancellationToken on every Task that EXECUTES work, Task.Run, Task.Delay and RunScriptAsync; a missing one means CancellationToken.None✅ Yesa token that fires faults the task, and one that is already cancelled never starts the body. The fault reads the awaited operation was cancelled before it completed, an engine message rather than a localized runtime one
a source-less bundle (--compile --source=strict)✅ Yesthe strip carries what a body IS, so a program whose top level waits on an async call runs from its bundle and prints what the file prints: the async-ness of a declaration travels with it, and a call from a compiled body hands its caller a Task either way. A body the compiler declined is still skipped and named in the export report
ConfigureAwait✅ Yes, as a no-opawait t.ConfigureAwait(false) awaits the same work: this engine has one pump and no synchronisation context to marshal a continuation away from, so the flag has nothing to change and the call answers the task itself
Task<T> results, ValueTask, await foreach✅ For the SPELLING, ❌ for an enforced payload typeasync Task<T> is the spelling and T is the body's result type, while the engine's Task stays UNTYPED at run time, so .Result is what carries the value. An enforced payload type, ValueTask and await foreach are still not there
a Task as a JSON value✅ Yes, as null by designa Task is a handle to running work rather than data, so there is nothing to write and nothing a reader could rebuild: Json.Serialize answers null for one, pending or complete, and for a task held in a list or a dictionary. C# writes the bookkeeping instead (Id, Status, IsCompleted) and that is just as unusable, so the rule is the same on both sides: serialize the INPUTS and the OUTCOME, never the task, which is what a job queue does (a payload plus a handler name). t.Status is a string and t.Result is the value
the outermost wait in a FILE✅ Yes, with await or with .Result / .Wait()a file's top level can await, so var r = await Work(); works there, and a file-level await SUSPENDS the run: the awaited task's completion resumes the same statement, so a host keeps control while the script waits (see the file's top level as an async entry). .Result and .Wait() keep waiting on the spot. Inside an async body use await and never .Result. Waiting drives the pump, so it cannot deadlock the way a CLR .Result can against a synchronisation context
two awaits in ONE expression, as in (await a) + (await b)✅ Yes in an async body and at a file's top levelan async body compiles, so a second await resumes at the next instruction instead of re-entering the statement, and a file's top level keeps an AWAIT JOURNAL per statement, so the second await is answered with the value it already produced instead of re-issuing the first. A body the compiler DECLINES (one holding an is pattern, a using body or a nested function) runs on the tree, where re-entry would re-issue the first await, so that shape is refused by name with the fix: var x = await a; var y = await b;
How it runs. The engine's suspension is cooperative and single-threaded: an await yields an awaitable to the coroutine pump, the pump wakes the body when the awaited Task completes, and a wait on the Task (.Wait(), .Result, or waiting on a combinator) is what drives that pump. An async body COMPILES and runs on the bytecode VM, where its await is the AWAIT opcode and the resume continues at the NEXT instruction (which is what lets one statement hold two awaits), and a body holding a try compiles too, so its catch catches a fault an awaited body raised. A body the compiler declines, one holding an is pattern, a using body or a nested function, is tree-walked instead, and there the once-per-statement await rule applies. At a file's top level the run driver is what suspends and resumes, which is what a host reads through slc_poll. The C#-flavoured surface above was added as a proof of concept, so treat the tables as the contract for now.
Coroutine Coroutine API Start, Pump, Sleep, Wait; or call a coroutine directly for a Generator

The Coroutine namespace provides static methods for managing coroutines. Functions containing yield are auto-detected as coroutines. Calling a coroutine function directly returns a Generator lazy, with no thread and no pump needed driven with MoveNext()/Current or foreach; Coroutine.Start() remains the pump-style API for background scheduling.

Coroutine.Start(fn, args..., autoStart?); // autoStart defaults to true Coroutine.Pump(); yield Coroutine.Sleep(ms); yield Coroutine.Wait(evt); var gen = myCoro(2); // direct call → Generator (no Start needed)
// Direct call → Generator: MoveNext()/Current arguments are PRESERVED on first resume int countTo(int max) { var i = 0; while (i < max) { yield i; i = i + 1; } return i; } var gen = countTo(2); // nothing runs until the first MoveNext() print(gen.MoveNext(), gen.Current); // True 0 argument 2 reached the body print(gen.MoveNext(), gen.Current); // True 1 print(gen.MoveNext()); // False the function finished // foreach iterates the same generator foreach (var v in countTo(3)) { print(v); } // 0, 1, 2 // Nested coroutines a coroutine calls another coroutine by bare name int pairs(int n) { var i = 0; while (i < n) { yield (i, i * 2); i = i + 1; } return -1; } int outer(int n) { foreach (var v in pairs(n)) { yield v; } return -1; } foreach (var t in outer(3)) { print(t[0], t[1]); } // 0 0, 1 2, 2 4
// Start and pump (background scheduling) var co = Coroutine.Start(myFunc); while (co.IsResumable) { Coroutine.Pump(); } // stops on Completed or Dead // Manual pump-style alternative: Coroutine.Start(fn, args..., false) + co.Resume() var co2 = Coroutine.Start(countTo, 2, false); print(co2.Resume()); // 0 first Resume reaches the first yield print(co2.Resume()); // 1 print(co2.Resume()); // 2 the return value; Status is now Completed (natural end) // Action vocabulary Continue ≡ Resume (safe on any status), Abort ≡ Dispose, // Reset = safe destroy (Dead; later Continue/Resume → null instead of throwing) var co3 = Coroutine.Start(countTo, 2, false); print(co3.Continue()); // 0 same as Resume() co3.Abort(); // → Dead, state freed (like Dispose) print(co3.Continue() == null); // True already Dead (Continue returns null) var co4 = Coroutine.Start(countTo, 2, false); co4.Reset(); // safe destroy → Dead (no exception) // Sleep inside a coroutine yield Coroutine.Sleep(1000);
The direct-call Generator path is AOT-safe: Generator<T> is preserved for NativeAOT builds, so scripts can call MoveNext()/Continue()/Current/Dispose()/Abort()/Reset() on a direct-call generator under AOT same vocabulary as the Coroutine instance (Resume()/Continue()/Dispose()/Abort()/Reset()). Coroutines run through the tree-walker (they are not VM-compiled), so they are skipped at bytecode export.
CoroutineStatus Coroutine lifecycle states

Values returned by co.Status. Lifecycle: NotStarted → Suspended/Waiting while running or awaiting a request → Completed (the body ran to its end/return naturally) or Dead (disposed, abandoned, or errored).

CoroutineStatus.NotStarted // not yet started CoroutineStatus.Suspended // yielded a value resumable CoroutineStatus.Waiting // yielded a request (sleep/http/…) resumable CoroutineStatus.Completed // body ran to its return/end finished naturally CoroutineStatus.Dead // disposed / abandoned / errored not Completed
// Hand-driven loops: use IsResumable so a naturally-completed (Completed) // coroutine stops the loop too (Status != Dead alone would spin forever on it). while (co.IsResumable) { Coroutine.Pump(); } if (co.Status == CoroutineStatus.Completed) { print("finished, return=" + co.LastYieldedValue); }
params Variable-length parameter collects excess call arguments into an array

The params keyword marks the last parameter of a function as a variable-length argument collector. When the function is called, any excess arguments beyond the required ones are collected into an Array (native object?[]). The parameter type must be Array or an array type like int[].

void printAll(params Array items) { foreach (var x in items) print(x); } printAll(1, 2, 3, "hello"); // items = [1, 2, 3, "hello"]
// Parameters can be passed individually or as an array literal int sum(params int[] nums) { var total = 0; foreach (var n in nums) total = total + n; return total; } print(sum(1, 2, 3)); // 6 params collect excess args print(sum([10, 20, 30])); // 60 single array literal also works

params can only appear on the last parameter. A function can have at most one params parameter. If a single argument is already an Array, it is passed through directly rather than double-wrapped.

Tail elements are by value. The array the callee receives is created for the call and filled with by-value elements, so a ref or out argument cannot occupy a tail position: there is no caller variable for the callee to write back to. Declare the parameter ref T[] xs and pass the array when the callee must write the array itself back.

.NET native methods with params are now supported e.g. Console.WriteLine(format, arg0, arg1, ...), string.Format(format, args...), StringBuilder.AppendFormat(format, args...). The interpreter detects [ParamArrayAttribute] on the last parameter and collects excess arguments into a typed array automatically.

Array literals vs. .NET params: A single array literal [a, b, c] passed to a .NET params method is not expanded it is passed as a single object argument. Always pass format values as individual arguments for .NET native methods like Console.WriteLine, string.Format, or StringBuilder.AppendFormat.

// .NET params methods work with multiple individual arguments Console.WriteLine("{0} {1} {2}", "Hello", "from", "params"); // Console table header with 13 positional args var row = "| {0,-4} | {1,-15} |"; Console.WriteLine("{0} {1} {2} {3} {4} {5} {6}", row, "Id", "Name", "CronExpr", "TzId", "MaxIter", "Status"); // string.Format var msg = string.Format("{0} + {1} = {2}", 1, 2, 3); // StringBuilder.AppendFormat var sb = new StringBuilder(); sb.AppendFormat("{0:D4} {1:F2}", 42, 3.14);
default parameter values Optional parameters with default values caller may omit trailing arguments

Function parameters can have a default value specified with = expr. When the caller omits trailing arguments, the default is used. Default parameters must appear after all non-default parameters.

void Greet(string name = "world") { print("Hello " + name); }
// Function with default int Power(int x, int exp = 2) { var r=1; while(exp>=0){exp=exp-1;r=r*x;} return r; } print(Power(3)); // 9 (3²) print(Power(2, 10)); // 1024 // Multiple defaults string Concat(string a = "a", string b = "b") { return a + b; } print(Concat()); // "ab" print(Concat("x")); // "xb" print(Concat("x", "y")); // "xy"
Default values work on named functions, lambdas, and class methods. They also work with params for variadic functions.
ref Pass argument by reference allows the callee to modify the caller's variable

The ref keyword marks a parameter as passed by reference. The callee can read and modify the caller's original variable. Works on function parameters and method parameters. Supports all value types: int, long, double, string, bool, char, structs, and class instances.

void Increment(ref int x) { x = x + 1; } var a = 5; Increment(ref a); print(a); // 6
// Swap two values void Swap(ref int x, ref int y) { var tmp = x; x = y; y = tmp; } var c = 10; var d = 20; Swap(ref c, ref d); print(c + "," + d); // 20,10 // With class instance mutating a field through ref class Box { public int val; } void DoubleBox(ref Box b) { b.val = b.val * 2; } var bx = new Box(); bx.val = 21; DoubleBox(ref bx); print(bx.val); // 42 // A FIELD, a PROPERTY or an ELEMENT can be passed by ref, and a ref local can point at one class RLBox { public int F; } void Bump(ref int v) { v = v + 1; } var h = new RLBox(); h.F = 3; Bump(ref h.F); // h.F is 4 ref int rf = ref h.F; // rf IS h.F rf = 30; // h.F is 30 int[] a = [1, 2, 3]; var re = ref a[1]; // the index runs ONCE re = re + 20; // a[1] is 22 Bump(ref a[2]); // a[2] is 4 print(h.F + "/" + a[1] + "/" + a[2]); // 30/22/4 // An `in` parameter is read-only and by value, and the keyword is optional at the call int Scale(in int v) { return v * 3; } var n = 4; print(Scale(in n) + "/" + Scale(n) + "/" + Scale(7)); // 12/12/21 // A REF RETURN: the call answers a REFERENCE, so reading it dereferences and assigning writes through int total = 0; ref int Slot() { return ref total; } Slot() = 9; // total is 9 ref int r9 = ref Slot(); // r9 IS total r9 = r9 + 1; // total is 10 print(Slot() + "/" + total); // 10/10 // A ref-returning METHOD is an lvalue the same way class Pool { public int n; public ref int Cell() { return ref this.n; } } var pool = new Pool(); pool.Cell() = 4; // pool.n is 4 ref int pc = ref pool.Cell(); // pc IS pool.n pc = pc * 2; // pool.n is 8 print(pool.Cell()); // 8 // All primitive types supported var rl = 50L; // long var rd = 10.0; // double var rs = "hello"; // string var rb = true; // bool var rc = 'A'; // char

Rules:

  • Both the declaration and the call site must use ref: Fn(ref x). Naming the keyword for a parameter that is not declared that way is an error, and the two keywords are not interchangeable: ref for an out parameter, or out for a ref one, is refused. The argument is never quietly passed by copy instead.
  • ref parameters cannot be used with const variables (throws ConstAssignment)
  • An argument passed by ref or out must be a VARIABLE, a FIELD or an ELEMENT (Fn(ref h.F), Fn(ref a[i])): a literal, a call and an operator result have no storage to write back to. An element's index is evaluated ONCE, and a bad index is refused at the call rather than on a later read
  • The variable a ref argument names must already hold the declared parameter type, because a reference is never converted: converting would retype the caller's variable. void P(ref int v) called as ref s where s holds "abc" is refused, and ref object is the spelling for "any variable". A numeric family still passes, so ref double accepts an int variable
  • A ref local binds a reference: ref int r = ref x; or var r = ref x;, and the target may be a variable, a field or an element (ref int r = ref h.F;). The local IS that storage, so a read dereferences it and an assignment writes through, an element's index is evaluated once, and the local travels into a lambda like any other capture. The written type is documentation: typeof(r) answers what the reference points at. Rebinding (r = ref y) is not supported
  • A ref overload and an out overload of the same parameters cannot coexist: a call cannot tell them apart, so the second declaration is refused
  • An in parameter is read-only and passed by value: int Scale(in int v). The keyword is optional at the call, a temporary is allowed (Scale(7)), and a body that writes the name, passes it by ref/out, or takes a ref local over it is refused WHERE IT IS DECLARED, with the fix named. The declared type still checks the argument
  • ref works in lambdas (fun(ref int x) => ..., where the fun keyword is required because (ref int x) => does not parse), constructors, and delegates, in classes and in structs alike
  • A ref return declares what the reference points at and answers the reference itself: ref int Slot() { return ref v; }. Reading a call dereferences (Slot() + 1), while Slot() = 9; and ref int r = ref Slot(); use the reference and write through it, on a free function and on a method (ref int Field() { return ref this.F; }). Such a body compiles, and so do both LVALUE uses: a plain read is a flat VM call, and for Slot() = 9; and ref int r = ref Slot(); the compiler marks the call so the VM hands the reference back instead of the value. A ref on a call that answered a VALUE is refused with the fix named, and a ref return of a LOCAL is allowed here where C# refuses it, because the reference is a heap cell rather than a native address
  • A ref argument cannot occupy a params tail position (see params)
  • ref works with events via delegate types that accept ref parameters (discouraged for multicast events), but an EVENT itself cannot be passed by ref: it holds a handler list, not a value
  • Coroutine Coroutine.Start() supports ref arguments
  • What it costs, and on which engine. A compiled body encodes a reference in bytecode (a slot reference for an argument, a cell the engine builds for a global, a field or an element) and the VM dereferences it; the tree walker closes a RefCell over a getter/setter pair per position. That is where the difference comes from: on the AOT build a loop passing a ref argument took 3% to 15% of the tree walker's time (a ref to a global or an out position about 5%), with allocations of the same order of magnitude apart. A ref LOCAL over a LOCAL variable is an ALIAS, the cheapest shape of the family (about 580 ns per iteration on the VM against 10,100 on the tree, and a few kilobytes allocated where the tree allocates megabytes); over a global, a field or an element it is a cell, so every read and write goes through it. A ref RETURN compiles too, and so do its two LVALUE uses: a read dereferences, `F(..) = 7;` writes through the reference, and `ref int r = ref F(..);` binds `r` to it. The compiler marks such a call so the VM hands the CELL back instead of the value (a plain read stays a flat VM call, so a compiled caller pays no interpreter re-entry), and the write goes through one helper the tree uses as well. A ref-returning METHOD is an lvalue too (box.F() = 7;, ref int r = ref box.F();). Two narrower shapes are the exceptions, and they differ in kind: a BARE call to the class's own method as an lvalue (Cell() = 12; inside a method) works, with that method's body walked rather than compiled, because its marker would have to sit under a receiver the arm builds first; and a call that NAMES its arguments cannot be assigned through at all (box.F(n: 0) = 9; is refused by the language, identically from a file and from a bundle, because a call that names its arguments is not a reference target, while READING it is fine). ref int r = ref F(..); also needs F to be provably a ref return, and the tree refuses it by name otherwise. assets/language/repl/bench/bench_ref_vm_tree.slc measures all of it in one process, switching engines with VmSetEnabled
  • Internally, ref is implemented via a RefCell wrapper that captures a getter/setter pair for the target; a field or an element reuses the very resolver a compound assignment writes through, so a reference and h.F = v are one storage
in A read-only parameter, and the foreach separator

in has two jobs, and neither is a boolean operator. Before a parameter's type it declares a READ-ONLY, by-value parameter (int Scale(in int v)): the body reads v and a write to it is refused, and the CALLER may write the keyword or leave it out, since the modifier is about the callee's side. In a foreach header it separates the iteration variable from the collection. Both spellings are keywords, so in cannot be a variable name, while In is an ordinary identifier (keywords are case-sensitive). The ref entry has the modifier's neighbours.

int Scale(in int v) { return v * 3; } var n = 4; print(Scale(in n) + "/" + Scale(n)); // 12/12, the keyword is optional at the call var sum = 0; foreach (var x in [1, 2, 3]) { sum = sum + x; } print(sum); // 6
out Pass argument by reference callee must assign a value before returning

The out keyword marks a parameter as an output parameter. Unlike ref, the caller's variable does not need to be initialized before the call. The callee must assign a value to every out parameter before the function returns, otherwise a runtime error is thrown. Available in functions, methods, lambdas, constructors, and delegates. The call site must name the keyword the parameter declares, out for an out parameter and ref for a ref one, because the two are not interchangeable. Class and struct constructors both take out parameters, and an out argument cannot occupy a params tail position.

Three call-site syntaxes

// 1. Existing variable variable must exist or is auto-created void InitValue(out int x) { x = 42; } var a; InitValue(out a); print(a); // 42 // 2. Inline declaration (C# 7.0 style) declares and captures in one step InitValue(out var b); print(b); // 42 // 3. Discard value is thrown away, no variable created InitValue(out var _); // true discard, no scope pollution InitValue(out _); // also discards, but _ is a real variable
// Multiple out params inline declaration void Split(out int first, out int second) { first = 10; second = 20; } Split(out var x, out var y); print(x + "," + y); // 10,20 // ref + out in same call void ReadThenInit(ref int source, out int dest) { dest = source + 5; } var src = 10; ReadThenInit(ref src, out var dst); print(dst); // 15 // With class constructor class OutCtor { constructor(out int created) { created = 2024; } } var obj = new OutCtor(out var val); print(val); // 2024 // With lambda var factory = fun(out int v) { v = 77; }; factory(out var res); print(res); // 77 // Discard with out var _ factory(out var _); // value discarded, no _ variable created

Rules:

  • Both the declaration and the call site must use out: Fn(out x)
  • The caller's variable does not need to be initialized beforehand out var name declares it inline; out name auto-creates it if undefined
  • The callee must assign a value to every out parameter before the function returns failure to do so throws: "The 'out' parameter 'X' must be assigned before the function returns."
  • A parameter cannot be both ref and out
  • out works in plain functions, class methods (instance and static), lambdas (fun and arrow), constructors, and delegates
  • out works with events (declared as delegate void Handler(out int x)) following C# conventions: technically supported, but discouraged for multicast events since only the last subscriber's assignment is observable
  • Type compatibility: When an out parameter has a named class type (e.g. List<int>, StringBuilder), assigning a value of an incompatible type throws TypeMismatch: "cannot assign value of type 'X' to out/ref parameter 'Y' of type 'Z'." Primitive types (int, string, double, etc.) are auto-coerced and not checked
  • Internally, out is implemented via the same RefCell mechanism as ref, but with an assignment tracker and the ability to capture undefined variables

▼ Classes & Structs

extends Single inheritance for classes

The extends keyword creates a class that inherits fields, methods, constructors, and events from a parent class. The child can override methods and must call super() in its constructor.

class Child extends Parent { constructor(params) { super(baseArgs); /* ... */ } }
class Animal { public string Name; constructor(string n) { this.Name = n; } public string Speak() { return "..."; } } class Dog extends Animal { public string Breed; constructor(string n, string b) { super(n); this.Breed = b; } public string Speak() { return "Woof!"; } } var d = new Dog("Rex", "Lab"); print(d.Name + " says " + d.Speak());

Access modifier defaults:

  • class / struct declarations → private (not visible from importing scripts unless marked public)
  • Class members (fields, methods) → private
  • Struct members (fields, methods) → private
  • Top-level functions → private (not exported from modules unless marked public)
  • Top-level const / var → public (module constants are visible to importing scripts)

Access matrix (class/struct declarations):

ModifierSame-fileImported moduleAs type arg (import)
none (defaults private)✅❌ blocked❌ blocked
private✅❌ blocked❌ blocked
protected✅❌ blocked❌ blocked
internal✅✅ accessible✅ accessible
public✅✅ accessible✅ accessible

Constructor access matrix:

ModifierSame-file globalImported class
none (defaults public)✅ callable✅ callable
public✅ callable✅ callable
private❌ blocked❌ blocked
protected❌ blocked❌ blocked (only via super())
internal✅ callable✅ callable

Member defaults: Class fields/methods default to private. Struct fields/methods also default to private. private/protected members are blocked from global code even in the same file.

Constructor access: Constructors support access modifiers too (public, private, protected, internal). A private constructor can only be called from within the class itself (singleton pattern). A protected constructor is only accessible from derived classes via super(). internal constructors are accessible from importing scripts. Default is private (same as fields).

Only single inheritance is supported. Generic classes use <T> syntax: class Box<T> { ... }. Access modifiers: public, private, protected, internal. Destructors via ~ClassName() { } adds automatic Dispose() method with inheritance chaining. Static members via static keyword on fields and methods. See assets/language/repl/core/class_access_test.slc, destructor_comprehensive_test.slc, static_test.slc.

new Create an instance: script class, struct, CLR type or bag

new creates an instance and answers it. The name after it is a script class or struct, a CLR type (new StringBuilder("ab"), which is what the CLR fallback resolves) or one of the bag types (new List<int>()). A CLR CONSTRUCTOR is chosen by the argument TYPES and not only by their count, so new StringBuilder("x") fills the builder and new StringBuilder(10) only reserves. An OBJECT INITIALIZER fills properties and fields in the same statement (new Box() { V = 5 }), which is also the only moment an init or get-only property can be given a value. The constructor and object-initializers entries have the rest.

class Box { public int V; public string Tag { get; set; } } var b = new Box() { V = 5, Tag = "t" }; print(b.V + "/" + b.Tag); // 5/t var sb = new StringBuilder("ab"); sb.Append("c"); print(sb.ToString()); // abc var list = new List<int>(); list.Add(3); print(list.Count); // 1
constructor Special method called when creating a new class or struct instance; static variant runs once per type

Constructors initialize a new instance. They can take parameters, assign fields, and call the base constructor via super(). Multiple constructors with different parameter lists are supported (overloading).

A .NET type's constructor is chosen by the arguments themselves. When several constructors accept the same NUMBER of arguments, the first whose parameters accept the values is used, so new StringBuilder("x") takes StringBuilder(string) and new StringBuilder(10) takes StringBuilder(int).

Alternative syntax: Instead of constructor(params), you can use the class name itself as the constructor name identical to C# syntax. Both forms are equivalent and share the same overload set:

public ClassName(params) { /* initialization */ } // same as constructor(params)

Restriction: Methods cannot share the same name as the class attempting to declare void ClassName() produces a parse error suggesting the ClassName(...) constructor syntax instead.

Static constructors (static constructor()) run automatically once before the first instance is created or the first static member is accessed. They are parameterless, cannot have an access modifier (public, private, etc.), and cannot reference instance fields via this. They run in base-to-derived order across the inheritance hierarchy like C# static constructors.

constructor(params) { /* initialization */ } // instance constructor static constructor() { /* one-time type init */ } // static constructor
// Instance constructors use class name or constructor() class Point { int X; int Y; public Point(int x, int y) { this.X = x; this.Y = y; } public constructor() { this.X = 0; this.Y = 0; } } var p1 = new Point(3, 4); // calls Point(int, int) var p2 = new Point(); // calls constructor() // ClassName() syntax identical to constructor() class NativeLib { private var _lib; public NativeLib(string dllName) { _lib = LoadLibrary(dllName); } ~NativeLib() { if (_lib != null) FreeLibrary(_lib); } } var nl = new NativeLib("user32"); // calls NativeLib(string) constructor // Static constructor runs once, auto-executed before first use class Shape { public string Name; private constructor(string n) { this.Name = n; } static Shape RedCircle; static Shape BlueSquare; static constructor() { Shape.RedCircle = new Shape("circle"); Shape.BlueSquare = new Shape("square"); } } print(Shape.RedCircle.Name); // circle (static ctor ran automatically)

Rules:

  • Instance constructors support access modifiers: public, private (singleton pattern), protected (only via super()), internal
  • Static constructors are always private and cannot have an access modifier or parameters
  • Static constructors cannot use this there is no instance at the time they run
  • The execution order is base class → derived class, matching C# semantics
destructor (~) Finalization method called when a class instance is garbage-collected or disposed

A destructor (also called a finalizer) is declared using the tilde ~ prefix followed by the class name, with no parameters and no return type. It is called automatically by the garbage collector when the object is collected, or explicitly via the built-in Dispose() method.

~ClassName() { // cleanup code }
class Resource { private IntPtr _handle; public bool Disposed; // plain field public Resource(IntPtr h) { _handle = h; } ~Resource() { if (this.Disposed) return; this.Disposed = true; print("cleaned up"); } } var r = new Resource(0); r.Dispose(); // calls destructor → "cleaned up" print(r.Disposed); // true

Important: Destructors are non-deterministic when called by the GC you cannot predict when (or if) the GC will run. For deterministic cleanup, call the built-in .Dispose() method on the instance to invoke the destructor immediately. Calling Dispose() multiple times is safe (the destructor should guard with a flag like Disposed).

Dispose() Uniform cleanup call real dispose for IDisposable/native resources, safe no-op otherwise

Dispose() is callable on every value (uniform "virtual dispose"). Behavior by receiver kind:

  • Script class instance invokes the class destructor chain (~ClassName) immediately for deterministic cleanup; you never need to define Dispose() yourself.
  • IDisposable .NET types (Mem.Buffer → MemBuffer, LoadLibrary → DynamicLibrary, File.OpenRead → FileStreamReader, Sqlite.Query → SqliteIterator, Process.Start → ProcessHandle, ...) releases the underlying resource.
  • Anything else (int, string, Dictionary, arrays, ...) safe no-op, never throws.
obj.Dispose();
class FileHandle { private IntPtr _handle; public bool Disposed; // plain field constructor(string path) { _handle = CallNative(...); } ~FileHandle() { if (this.Disposed) return; CallNative("CloseHandle", _handle); this.Disposed = true; } } var fh = new FileHandle("data.txt"); // use fh... fh.Dispose(); // deterministic cleanup: destructor runs now // Uniform no-op on non-disposable values var dict = new Dictionary<string, int>(); dict.Dispose(); // safe no-op dict stays usable 42.Dispose(); // safe no-op

For script classes, Dispose() is always available write cleanup code in the destructor and call .Dispose() for deterministic release (file handles, native pointers). The destructor should be idempotent (guard re-entry with a flag like Disposed). For non-disposable values the call is a harmless no-op, so .Dispose() can be used uniformly in cleanup paths.

extension members Declare members on a type you do not own C# 14 `extension` blocks

An extension block declares members on a type the script does not own. A member declared public static is called on the extended type itself (List<int>.Create()); a member written without static is called on a value of the extended type ("abcd".Len()), with the receiver bound as this. A block may be written at top level, or inside a static class container: a container class that is not static is refused, as it is in C#, and a top-level block needs no container at all. A block registers for the file that DECLARES it and no other: an extension block declared in an imported module does not reach the importer (the import entry has the measurement), so declare it where it is used. A nested static class is a container too (class Outer { public static class Exts { extension(…) { … } } }): static is accepted wherever a nested class or struct is declared. The extended type is matched by name and arity, never by reflection, so a List<int> value reaches List<T>.

// ── 4. A block over an INTERFACE: it speaks for every value that MATCHES the contract ── interface ISized { int size(); } extension(ISized) { public string label() { return "size " + this.size(); } } class Measured implements ISized { public int size() { return 3; } } // declared the contract class Loose { public int size() { return 5; } } // merely shaped like it struct Pt implements ISized { public int size() { return 7; } } // and a struct var p = new Pt(); print(new Measured().label()); // "size 3" print(new Loose().label()); // "size 5": structural matching reaches the block too print(p.label()); // "size 7" // A STATIC member cannot work this way, and is refused with the reason: // 'ISized' is an INTERFACE, and a static member is reached through a TYPE name: a value never reports an // interface, so that member could never answer. Write it as an INSTANCE member, which a block over 'ISized' // provides to every value that matches the contract.
The target is a TYPE, and a receiver reaches its base classes too. Dispatch matches the receiver's type name, then each base class up the chain NEAREST FIRST, so a Dog value reaches a block on Animal and the most derived block wins. object is the last step of that walk, which makes extension(object) the one spelling that speaks for every value. What is still refused: extension<T>(T), a block cannot extend its own type parameter, and a CONTRACT name (Iterable, RandomAccess, Function, Class, Struct), which is a guard for is/as rather than a type. A STATIC member is reached through the type it was written for, so it is not inherited by a derived type name: the walk applies to values.
extension[<T>] (Target [name]) { public static ReturnType Member(args) => …; public ReturnType Property => …; }
The receiver may be NAMED. extension(string s) gives the block's members a second spelling of the value beside this, as C# 14 does: inside every member of that block s and this are the same object, and a member's own parameter of that name still shadows it. The name is an alias, not a parameter it cannot be reassigned as an argument, and a static member of the block has no receiver, so a body reading it is refused exactly as one reading this is.
// ── 0. A NAMED receiver: `s` beside `this` ────────────────────────────────── extension(string s) { public int Len() => s.Length; // the name is the receiver public int Both() => s.Length + this.Length; // and `this` is the same value } // Anonymous form writes no name at all, and the members below behave identically. extension(string) { public int Len2() => this.Length; } // ── 0b. A PROPERTY: computed, because a block adds no storage ───────────────── extension(string s) { public int Len => s.Length; // read as a property, no parentheses public int Capped { get => s.Length > 3 ? 3 : s.Length; } // get only } extension(string) { public static string Kind => "text"; } // reached through the TYPE print("abcd".Len); // 4 print("abcde".Capped); // 3 print(string.Kind); // text // A setter sees the assigned value as `value`, and writes it wherever the block says: // `public int X { get => …; set { holder = value; } }` is the shape on a receiver you own.
// ── 1. The basic shape: a block at top level, one INSTANCE member ─────────── // Without `static` the member is reached on a VALUE of the extended type, and the // receiver is bound as `this`. The type is matched by name and arity, never reflection. extension(string) { public int Len() => this.Length; public string Twice(string sep) => this + sep + this; } print("abcd".Len()); // 4 called on any string print("ab".Twice("-")); // ab-ab this, then the parameters // ── 2. Both halves, and a class YOU declared ─────────────────────────────── // `public static` is the TYPE half: it is called on the extended type itself. extension(string) { public static string Greet() => "hello"; public static int Measure(string s) => s.Length; } print(string.Greet()); // hello through the TYPE print(string.Measure("abcd")); // 4 class Animal { public string Name = "rex"; } extension(Animal) { public string Shout() => this.Name + "!"; } print((new Animal()).Shout()); // rex! a script class instance is a receiver // ── 3. A GENERIC target: T comes from the receiver ───────────────────────── extension<T>(List<T>) { public int HowMany() => this.Count; } // A list literal is an ARRAY, not a List ToList() is what makes a real List<int>. var xs = [1, 2, 3].ToList(); print(xs.HowMany()); // 3 a List<int> value binds T = int (an int[] would not match) // ── 4. Where a member already exists, the value's OWN member wins ────────── // C# spec 7.6.5.2: an extension never shadows what the type already answers with. extension(string) { public int Trim() => 999; } print(" a ".Trim()); // a String.Trim wins: the extension is declared but never used class Beast { public string Shout() => "own"; } extension(Beast) { public string Shout() => "ext"; } print((new Beast()).Shout()); // own the class's own member wins // ── 5. Advanced: T bound from the CALL SITE, a returned literal typed by the ─ // declared type, and the two halves that must not leak into each other extension<T>(List<T>) { public static List<T> Create() => []; public static T[] None() => []; } print(typeof(List<int>.Create())); // List<int> [] became a List<int> print(typeof(List<string>.None())); // string[] and it follows the call site extension(string) { public static string Bark() => "bark"; } print(string.Bark()); // bark try { print("x".Bark()); } // Method 'Bark' not found on type String -- the value half's refusal catch (var e) { print(e.Message); } // the refusal names the member it looked for

extension is a contextual keyword, exactly like enum: it is a declaration keyword only where a declaration may start, so a variable named extension keeps working.

How "the value wins" is checked. By NAME and ARITY over every overload, plus properties and fields, following the interpreter's comparer, since the check can only block an extension. The first implementation asked GetMethod(name, flags), which throws AmbiguousMatchException as soon as a type has two overloads of that name, as String.Trim does, inside a try with an empty catch, and a swallowed exception reads as "owns no such member". That let an extension shadow String.Trim until crash_extension_members.slc declared the collision and caught it; the check that pretended to guard the rule had declared no block at all.
Instance members. A member written without static is reached through a value of the extended type, "abcd".Len(), a.Shout(), xs.HowMany(), and only when nothing the value owns answers: instance members take priority over extensions (C# spec 7.6.5.2), so " a ".Trim() still calls String.Trim, and a class's own Shout() still wins. Script classes, structs and the built-in types all work as receivers, and a List<int> value reaches extension<T>(List<T>) by name, and its type parameter is bound from the RECEIVER a List<int> value binds T = int and a dictionary binds BOTH of its parameters, a generic class instance the arguments it was instantiated with so the signature and body are concrete on either half.
A member is a METHOD or a PROPERTY, and nothing else. A block declares methods and COMPUTED properties: a field, an operator, an event, a constructor, an indexer or a nested type is refused at declaration, because these are what a block adds from outside a type. A property has no storage here (the block adds none), so its only forms are Name => expr; and Name { get => …; set { … } }, and an auto-accessor (get;) is refused with that reason. What a METHOD MAY be is broad: ordinary parameters, params, its own type parameters (public string Tag<U>(U v), with U inferred at the call), a coroutine body (yield), and it may be written public or private (the modifier is accepted and restricts nothing). A ref or out parameter is ordinary too: the call site names the variable to write back to, exactly as a function's does ("abc".Fill(ref n)). One shape is refused with the reason: this, or the receiver's name when the block gave it one, inside a static member, because a static member has no receiver. A name may be declared once per target and per half: two members with the same name are a duplicate even when their parameters differ (O() next to O(int)), so extension members do not overload, while one static and one instance member of the same name are two members, each reached through its own door (string.Dual() and "x".Dual()). An OPERATOR is `static` and takes BOTH operands (a class operator takes only the other one, because its receiver is the left), and one of them must be the extended type, which is what makes it findable. A PROPERTY and a method may share a name: they are different members, as they are in C#.
What is refused. A duplicate member for the same target is refused at declaration, and a block whose type parameters do not match the target's arity (say extension<T, U>(List<T>)) is refused with the count it expected. The target must be a NAMED type: extension<T>(T), a CONTRACT name (Iterable, RandomAccess, Function, Class, Struct, guards for is/as, not types), and an ARRAY (extension<T>(T[]), extension(string[])) are each refused with the reason and the spelling that works, because a block over any of them would register and then never fire. A static member no block declares reports No static extension member 'X' for 'List<int>', and the two halves do not leak into each other: a public static member is not reachable through a value, and an instance member is not reachable through the type.
A member's NAME follows the interpreter's case flag. Member names are compared with the interpreter's own comparer, like every other member lookup, so in the default (strict) mode Len and len are different members - "abcd".len() is an error there and resolves under .lax. The extended TYPE name follows the interpreter's comparer, like every other name.
Blocks register in the order they run, so a member is declared before its first use, as with any other top-level statement.
Type arguments are BOUND, and a returned literal is typed by them. The block's type parameters are bound from the call site's arguments, matched positionally against the extended type's, so List<int>.Create() instantiates the member with T = int (its parameters and return type become concrete). A member whose body is nothing but a returned list literal then takes its container from that declared type C# collection expressions: List<T> Create() => [] hands back a List<int>, and T[] None() => [] an int[]. Anywhere else the declared type stays descriptive, as it is everywhere in this language: a body computing a string for a declared int still returns the string, and a literal that reaches a var first loses the expectation.
Which engine runs what (VmStats() counts function invocations, not statements). A compiled function that calls an extension member stays on the bytecode VM: the type reference travels as the same TypeInfo the engine already carries for is, and the VM delegates the member lookup to the same registry the tree uses. A public static member's body is compiled as well, as long as its block has no type parameters. An instance member's body runs there as well it is compiled with a method's context and invoked with the receiver as the trailing this local. A generic block's member is instantiated per call site, and that instantiation is compiled too: the concrete clone has no type parameters left, so it runs flat as well. What stays interpreted is what the compiler cannot take: a coroutine member (wrapped the way a coroutine method is, so the interpreter walks it while it yields), and a body using a construct it declines such as a try/catch or a pattern match. The values are identical either way, which is what crash_extension_members.slc asserts.

Against C# 14's own extension blocks. The table is this language beside that spec, so what to expect is a lookup rather than a guess. A cell that differs is spelled out; the last table is what this language has and C# does not.

FeatureC# 14ScriptLangCore
Where a block may sit
At top level, no container✘ a static class is required✔: a top-level block needs no container
Inside a static class✔✔
Inside a class that is not static✘✘
Nested inside another type✘ the class must be non-nested✔: a nested static class is a container
A generic container (static class E<T>)✘ non-generic only✔
The receiver
Unnamed, extension(string)✔ this is the STATIC block✔ and the same block holds instance members too: static is per MEMBER, and the receiver is always this
Named, extension(string s)✔ the receiver becomes a parameter of that name✔ the name is a second spelling of this inside the block
ref / in / ref readonly / scoped receiver✔✘ a parse error
where T : … constraints✔✘ a parse error
Matching a base type or an interface✔ an implicit conversion from the receiver✔: the base CLASS chain, nearest first, with object last. An INTERFACE IS a target: the block speaks for every value that MATCHES the contract, nominal or structural, and a contract name such as Iterable stays refused
What a member may be
Instance method✔✔ this is the receiver
Static method✔✔ reached through the TYPE
Instance property (get/set, no backing field)✔: computed, no backing field✔: computed, Name => expr; or Name { get => …; set { … } }
Static property✔✔: reached through the type
User-defined operator (static), incl. += in an instance block✔✔: both operands, and one of them is the extended type. Compound += comes free, since the language desugars it
params parameters✔✔
The member's own type parameters✔✔ inferred, or written as Tag<long>(9)
Events, fields, constructors, indexers, nested types, finalizers✘ not supported yet✘ refused
Resolution and scope
A real member wins over an extension✔✔
Invoked as if it were on the receiver✔✔
Overloading between candidates✔ normal overload resolution, then the ambiguity is reported✘ one member per name and per half: O() next to O(int) is a duplicate
What carries a blockthe using scope of the enclosing namespacethe FILE that declares it, an imported block does not reach the importer
The old this-parameter syntax✔ kept working✘ a parse error; the block form is the only spelling

And the other direction here, and not in C# 14's spec (each is usable today, and pinned by the extension suites):

/tr>
What this language hasC# 14
A block at top level, with no container at alla non-static class, or none, is refused, the class is required
A NESTED static class as the containerthe class must be non-nested
A GENERIC container classnon-generic only
ONE block holding both halves, chosen per member (static on the member), so Dual() and static Dual() live side by sidethe RECEIVER's shape decides, so that is two blocks, extension(string s) and extension(string)
A member reaching a SIBLING through this (public int Doubled() => this.Len() * 2;)no this in an extension body, the receiver is a parameter
A COROUTINE member (public int Steps() { yield 1; yield 2; })no coroutines in the language
Task.FromResult(value)✅ Yesa Task that is ALREADY complete and carries the value, the pair of Task.CompletedTask, so Task<int> A() => Task.FromResult(42); is a legal forwarder, awaited or read through .Result
RunScriptAsync(source [, concurrent])✅ Yesa nested script run handed back as a Task, so it composes (await, Task.WhenAll) instead of blocking. By default the run is PUMP work, performed on the next pump pass, so nothing runs on another thread; RunScriptAsync(src, true) starts it on a background thread the way Task.Run does. Both accept an optional CancellationToken, told apart from the flag by its TYPE, and a token that has already fired means the run never starts
interface A named contract of method signatures a class declares it implements

An interface declares a contract: a name and the method signatures a class must provide. A class says what it implements with implements, after its optional base class, and the engine checks it when the CLASS DECLARATION EXECUTES, before any instance exists, so a missing member is reported at the declaration rather than at the first call. An interface is checked TWICE, and both readings hold. A class that writes implements is validated when its declaration executes (so a missing member is refused at the declaration), and any value that provides every member a contract demands ALSO matches it structurally, whether or not it wrote implements: implements is a promise you state on purpose, and is asks the shape. An interface is declared at the top level, and a declaration is a statement, so an interface must run before the class that implements it and before the interface that extends it.

interface Name [extends Other[, More]] { ReturnType Member(args); // or ... { default body } }
// ── 1. The basics: a contract, a class, and what `is` says ──────────────────── interface IShape { int area(); // abstract: the class must implement it string describe() { return "a shape of " + this.area(); } // DEFAULT: inherited when the class writes none } class Square implements IShape { public int area() { return 16; } } var s = new Square(); print(s.area()); // 16 print(s.describe()); // "a shape of 16": the default body reached the class's own member print(s is IShape); // True var view = s as IShape; // the SAME value: an interface reference is a checked view, and nothing is wrapped
// ── 2. A property is a NAME plus the shape a member must have ───────────────── interface ISized { int Size { get; set; } // a FIELD or a property of that name answers this int Doubled => this.Size * 2; // a default PROPERTY: served when the value writes none } class Box implements ISized { public int Size; } // the field answers both accessors struct Point implements ISized { public int Size; } // and a struct's field does too var box = new Box(); box.Size = 3; print(box.Doubled); // 6 var p = new Point(); p.Size = 5; print(p.Doubled); // 10 // ── 3. What a refused declaration says ─────────────────────────────────────── interface INamed { string name(); } class Bad implements INamed { } // REFUSED when the class declaration runs, before any value exists: // Class 'Bad' implements 'INamed' but does not implement 'name/0'. // Add 'public <type> name() { }' to 'Bad', or give 'INamed.name/0' a default body. // The ARITY is part of the contract, so `public string name(int x)` is refused with the same words.
// ── 4. Two contracts, one name, two bodies: the contract is named at the CALL SITE ── interface IShapeA { int area(); } interface IContainerA { int area(); } class Both implements IShapeA, IContainerA { int IShapeA.area() { return 10; } // not in the class name table: reached by naming its contract int IContainerA.area() { return 20; } } var b = new Both(); print(IShapeA.area(b)); // 10 print(IContainerA.area(b)); // 20 print(b is IShapeA); // True, and True for IContainerA: one name satisfies both demands // b.area() IS refused, with the spellings to write instead: // 'area/0' is an EXPLICIT implementation on class 'Both', so it is not in the class name table. // Name the contract you mean: IShapeA.area(value) or IContainerA.area(value) // ── 5. Inheritance, an override, and the nearest one winning ────────────────── interface IRoot { int area(); string who() { return "shape"; } } interface IScaled extends IRoot { string IRoot.who() { return "scaled"; } } // an OVERRIDE, named by contract interface IScalable extends IRoot { void scale(int k); } class Grower implements IScaled, IScalable { public int area() { return 1; } public void scale(int k) { } } var g = new Grower(); print(g.who()); // "scaled": the NEAREST override wins print(IRoot.who(g)); // "shape": naming a contract reaches THAT contract's body print(g is IRoot); // True, through the parent // ── 6. A shape is enough, a trait matches everything, a library value is not a shape ── interface IShaped { int area(); } interface IMarker { } // a contract that demands nothing class Loose { public int area() { return 7; } } // never wrote `implements` print(new Loose() is IShaped); // True: it PROVIDES every member the contract demands print(new Loose() is IMarker); // True: a trait matches every class and struct print("abc" is IShaped); // False: a library value's surface belongs to the library // ── 7. A generic contract, and an extension block over a contract ───────────── interface IBox<T> { T get(); } class IntBox implements IBox<int> { public int get() { return 7; } } print(new IntBox() is IBox<int>); // True print(new IntBox() is IBox<string>); // False: the ARGUMENTS are part of the match // `class Bad implements IBox { }` is refused: // 'IBox' is a GENERIC interface, so write its arguments: `IBox<T>`. // A generic contract is matched by DECLARATION only, since a shape cannot witness the arguments. interface IShaped2 { int area(); } extension(IShaped2) { public string tag() { return "area:" + this.area(); } } class Declarer implements IShaped2 { public int area() { return 3; } } class Shaped { public int area() { return 5; } } struct Point2 implements IShaped2 { public int area() { return 7; } } var pt = new Point2(); print(new Declarer().tag()); // "area:3", a class that declared the contract print(new Shaped().tag()); // "area:5", a class that merely matches it print(pt.tag()); // "area:7", and a struct
An interface declares methods and properties. A property is that name plus the SHAPE a member must have, and a body on an accessor is a default; a field or a nested type cannot be a member of one, because an interface owns no storage. A member written as ReturnType Name(args); is abstract and every implementing class must provide it; a member with a body is a DEFAULT, and a class that writes none inherits it. One class method of the right name and arity satisfies two interfaces that demand it, and an implementation in a BASE class satisfies the contract too.
Checked at the declaration, with the member and its arity named. A class that implements a contract without implementing a member is refused where it is declared, and the message names what is missing and what to add: Class 'Bad' implements 'IShape' but does not implement 'area/0'. Add 'public <type> area() { }' to 'Bad', or give 'IShape.area/0' a default body. The arity is part of the contract, so area(int x) does not satisfy area().
An extension target, and one thing it cannot carry. A block over an interface speaks for every value that MATCHES the contract, nominal or structural, so extension(IShape) serves a class that declared it and a struct that merely has the members; a STATIC member in such a block is refused, since a static member is reached through a type name and a value never reports an interface. The built-in names (Iterable, RandomAccess, Function, Class, Struct) are guards for is/as rather than contracts, so declaring an interface with one of those names is refused.
The structural reading: a contract is a shape. x is I is True when the value PROVIDES every member I demands, name and arity, so a class or a struct that never wrote implements still matches, and a match brings the interface's DEFAULT bodies with it: such a value can call a member the interface supplies even though it declared nothing. A member with a default body is not asked for (the interface supplies it), a member of the wrong ARITY does not count, and a contract that demands nothing matches every class and struct, which is how a defaults-only trait is written. Only a script class or struct matches, so "abc" is ISomething is False rather than an error: a library value's surface belongs to the library.
Explicit implementations: the contract is named at the call site. A member can be qualified by the interface it serves, int IShape.area() { ... }. Dispatch is by name, so the receiver's type cannot differ per contract: such a member is deliberately NOT in the class's name table, and it is reached by naming the contract, with the value as the first argument, IShape.area(value). That is what lets two contracts demand one name with two different bodies, and a bare call is refused with the spellings to write: 'area/0' is an EXPLICIT implementation on class 'Both', so it is not in the class name table. Name the contract you mean: IShape.area(value) or IContainer.area(value). An explicit member satisfies exactly the contract it names and never another one, a member the value itself owns is still called on the value, and a DEFAULT body running inside a contract composes through that same contract, so this.area() inside IShape.describe reaches the IShape implementation. A struct may carry explicit members the same way.
Generic contracts are TEMPLATES, and one is matched by DECLARATION. interface IBox<T> declares one; a class instantiates it as implements IBox<int>, and the closed form is what the engine records and answers is IBox<int> for, so the ARGUMENTS are part of the match: IBox<int> and IBox<string> are two different contracts, and a bare IBox is refused with the recipe write its arguments: `IBox<T>`. A generic contract is matched by DECLARATION only, because a shape cannot witness which arguments were written, so a value that merely has the members does not match one. An interface may extend an instantiated contract (interface ID extends IBase<int>). A member is still pinned by NAME and ARITY, as everywhere else in a contract, so the argument types are not checked. Not here: variance, and constraints, since this engine parses no where clause anywhere yet.
What `is` and `as` mean here. x is I is True when the class of x, or one it inherits from, declares I (or an interface that extends it), and False for null. x as I is the same value when that holds and null otherwise: an interface reference is a checked view, so nothing is copied and nothing is wrapped.

Against the interface rules of C#. The table is this language beside that spec, so what to expect is a lookup rather than a guess. A cell that differs is spelled out, and a third mark means ALLOWED BY A DIFFERENT RULE, which the cell states. Every row below was measured on the shipped engine, and each refusal quotes the message it produces.

FeatureC#ScriptLangCore
What an interface member may be
An abstract method✔✔ int area();
A method with a body (a default)✔ C# 8✔ int describe() { ... }, served where nothing else answers
A property (abstract or with a body)✔✔ a property is a NAME plus the SHAPE a member must have: int Area { get; } demands a readable member, { get; set; } a readable and writable one, satisfied by a field or by a property on the implementing type, and a body (Area => expr; or { get => ...; }) makes it a DEFAULT
An indexer✔✘ Expected '(' after the name of a method, or '=>' or '{' for a property: an interface declares methods and properties, and a member may carry a DEFAULT body
An event✔✘ Expected a method or a property in the interface body. An interface declares METHODS and PROPERTIES, so a field or a nested type cannot be a member of one, and a property is written with accessors (`{ get; }`) rather than as a field
A static member (field, method, property)✔ C# 8✘ refused by the same rule as an event: Expected a method or a property in the interface body, so static is not a modifier an interface member takes
static abstract / static virtual, operators✔ C# 11✘ refused at the same place (Expected a method or a property in the interface body): it needs static abstract members and constraints, and constraints are missing engine-wide
A generic interface (interface I<T>)✔✔ a contract is a TEMPLATE: interface I<T> declares it, implements I<int> instantiates it, and is I<int> asks for it. A SCRIPT contract is matched by DECLARATION only, since a shape cannot witness the arguments, while a CLR one is matched by the arguments the value carries; a generic written WITHOUT them is refused with the fix in the message, and an unknown argument is refused naming the name (see the CLR interfaces entry)
Variance on a type parameter (in / out)✔✘ variance is not implemented, and the parse says so: Expect '>' after the interface's type parameters. (the in is then read as an identifier, which also draws the reserved-keyword warning)
A where T : ... constraint✔✘ constraints are missing engine-wide: no where clause is parsed anywhere, and the clause is refused where it would sit (Expect '{' before the interface body.)
An access modifier (public, private, protected, internal)✔ C# 8, private helpers are the point✘ a member is written bare, and a modifier is refused as a member that is neither a method nor a property (Expected a method or a property in the interface body); the ACCESS of the implementing member uses this language's own rules
virtual, abstract, sealed, override on a member✔✘ refused at the member (Expected '(' after the name of a method, or '=>' or '{' for a property): a default is always virtual (a class member always wins) and there is no sealed to stop it
A nested type (class, struct, enum, delegate)✔ C# 8✘ Expected a method or a property in the interface body, the refusal that names what an interface may declare
An instance field, constructor, finalizer or instance operator✘ C# rejects these too✘ An interface declares METHODS and PROPERTIES, so a field or a nested type cannot be a member of one, and a property is written with accessors (`{ get; }`) rather than as a field; a constructor is refused earlier, at Expect the interface member's name.
An abstract auto-property (int Area { get; set; })✔✔ it PARSES, and it is not storage here: a property is a NAME plus the SHAPE a member must have, so { get; set; } demands a readable and writable member (row 3 above)
Inheritance and dispatch
Multiple interface inheritance (interface A : B, C)✔✔ interface IC extends IA, IB: every parent's members are required, and is answers for each
A parent default is inherited by an implementer✔✔ a class implementing only the child answers the parent's default
One name demanded by two contracts, one implementation✔✔ one member of the right name and arity satisfies both
An EXPLICIT implementation (void IFoo.Bar())✔✔ grounded, and spelled at the CALL SITE: int IShape.area() { ... } is reached as IShape.area(value)
...and the bare name of one✔ it is hidden⚠ it is not in the class name table, and asking for it says which contract to write: 'M/0' is an EXPLICIT implementation on class 'OnlyExpl', so it is not in the class name table. Name the contract you mean: IX.M(value) (two contracts are both listed). A class that ALSO has an ordinary member of that name answers the ordinary one by the bare name, which is C#'s own rule
A derived interface OVERRIDES a parent default with a body (void IBase.M() { })✔ C# 8, the explicit form✔ a derived interface writes the override NAMED BY ITS CONTRACT (string IBase.M() { ... }), the nearest override wins, a re-declaration of the member makes it abstract again, and naming a contract reaches that contract's own body
Two unrelated interfaces with a default for ONE member (a diamond)✘ an error unless the class overrides it✔ refused LOUDLY, the same rule as C#, and the message names both the member and every contract to write: 'Who/0' has a DEFAULT in both 'ID1' and 'ID2', and 'NoAnswer' does not implement it. Add the member to its own type, or name the contract you mean: ID1.Who(value) or ID2.Who(value)
A default is visible on the VALUE by its bare name✘ C# 8 requires ((IFoo)obj).M()⚠ served by the same miss path a member goes through, so obj.describe() works: that is what a duck-typed language means
Who implements, and how it is reached
A class declares what it implements✔ nominal✔ implements, validated when the CLASS DECLARATION runs, naming the member, its arity and the recipe
A STRUCT as an implementer✔ C# 13✔ a struct DECLARES implements, validated when its declaration executes, and it matches a contract structurally as well
is, a cast, and a call through the interface✔✔ is and a cast are one membership test, and a cast yields the SAME value (no wrapper). A call through the contract, IFoo.M(obj), reaches an EXPLICITLY implemented member ONLY; for a member the value itself owns the bare name is the way, and naming the contract says so: 'IA' has no member 'M/0' that 'Two' implements EXPLICITLY. Write `IA.M(value, ...)` to reach an explicit implementation, and `value.M(...)` for a member the value itself owns
An extension member on an interface✔ C# 14✔ a block over an interface speaks for every value that MATCHES it, nominal or structural, and a STATIC member in one is refused

What this language has and C# does not. Two rules, both measured, and both are the same property seen twice: a declared contract is also asked of a value as a SHAPE.

FeatureC#ScriptLangCore
A value matches a contract WITHOUT declaring it✘ C# is nominal✔ a class or struct that provides every member matches, and a match brings the interface defaults with it
A contract that demands nothing (a trait)✘ a marker interface still has to be declared✔ it matches every class and struct, which is how a defaults-only trait is written
implements The interfaces a class or struct fulfils

implements lists the interfaces a class or struct fulfils, with several separated by commas: class Dog implements IAnimal, INamed. It is a CONTEXTUAL word, read as a clause only right after the class's optional extends parent, so a field or a method named implements is unaffected. A member the interface declares and the type does not is refused where the type is declared, and an instance satisfies the interface afterwards: d is INamed answers true, which is how a collection of one interface type can hold several implementations. The interface entry has the default-body and property rules.

interface INamed { string Name(); } class Dog implements INamed { public string Name() { return "Rex"; } } var d = new Dog(); print(d.Name() + " is INamed: " + (d is INamed)); // Rex is INamed: True
class Reference type with fields, methods, constructors, inheritance

Supports single inheritance, access modifiers, nested classes, operator overloading, and events. Classes can also be generic: class Box<T> { ... }.

class Name extends Base { // fields, methods, constructors }
class Point { public int X; public int Y; constructor(int x, int y) { this.X = x; this.Y = y; } public int Sum() { return this.X + this.Y; } } var p = new Point(3, 4); print(p.Sum()); // 7 // Nested class private inner class accessed by outer class method class WithPrivateInner { private class PrivateInner { public static string Hidden = "secret"; } public static string GetSecret() { return PrivateInner.Hidden; } } print(WithPrivateInner.GetSecret()); // "secret" // Nested struct inside a class class Outer { public struct InnerPoint { public int X; public int Y; } public InnerPoint Pos; } var o = new Outer(); print(o.Pos.X); // 0 (default)

See the static entry for details on static members, and the generics entry for type parameter syntax.

operator Declare an operator overload on a type

operator declares an overload as an ordinary method whose name is the token itself, and because the LEFT operand is this it declares EXACTLY ONE parameter: public Pt operator +(Pt other) adds this and other. The tokens are + - * / % < > <= >= == !=. A class or struct that declares one is used like a built-in on both engines, and a token the type does NOT declare is the engine's own refusal (Operator '+' is not defined for 'Bare') rather than a silent numeric answer. The class and struct entries show where the body sits among the other members.

class Pt { public int X; public Pt operator +(Pt other) { var r = new Pt(); r.X = this.X + other.X; return r; } } var p = new Pt(); p.X = 2; var q = new Pt(); q.X = 3; print((p + q).X); // 5
record Reference type with structural (value) equality == compares fields, not references

A record is declared like a class but with structural value equality: two record instances are == when all their fields are equal (compared recursively), regardless of whether they are the same object. Plain classes keep reference equality (== is identity).

record Point { public int x; public int y; }
record Point { public int x; public int y; } var p1 = new Point(); p1.x = 1; p1.y = 2; var p2 = new Point(); p2.x = 1; p2.y = 2; print(p1 == p2); // True (structural equality) // Nested records compare recursively record Inner { public int v; } record Outer { public Inner inner; public string tag; } // Records support constructors like classes record Person { public string name; public Person(string n) { name = n; } }
Structural equality applies to both the tree interpreter and the bytecode VM. Records work with ==/!=; enums and null semantics follow the same value-aware equality used by match patterns.
enum Named integer constants define a set of related values

Enums define a set of named integer constants. Members auto-increment from the previous explicit value (starting at 0). Values can be explicitly assigned with = expr. Enums are exposed as static fields on a synthetic class, so members are accessed via the enum name.

enum Color { Red, Green, Blue } enum Http { OK = 200, NotFound = 404 }
// Access members via the enum name print(Color.Red); // 0 print(Color.Blue); // 2 // Explicit values print(Http.OK); // 200 // Auto-increment after explicit value enum Mixed { A, B = 10, C } print(Mixed.A); // 0 print(Mixed.B); // 10 print(Mixed.C); // 11 // In switch/match var c = Color.Blue match { 0 => "red", 1 => "green", 2 => "blue", _ => "?" };
Enums can be declared at the top level. Use public to export them from modules. Access modifiers: public, internal, private (default). The underlying type is always long. The underlying type is long, and a member carries its enum as well: typeof(Color.Red) is "Color", Color.Red is Color and Color.Red is Enum are both true, and Json.Serialize(Color.Red) is 0 - while Color.Red is long stays true and arithmetic, comparison and match keep working on that underlying value. The enum's own name is matched as any script-declared type name is, exactly: Color.Red is color is an unknown-type error (in .lax too), while a CLR type name is written as C# spells it (DateTime): the lowercase forms were retired, and only .lax accepts another case. That is how the registry is keyed. Json.Serialize(Color) serializes an enum type as a JSON object: {"Red":0,"Green":1,"Blue":2}.
readonly Prevents mutation of a struct after construction readonly struct

The readonly modifier on a struct prevents field mutation after the constructor completes. Fields can only be set inside a constructor or via a with expression (which bypasses the restriction during the non-destructive copy). Accessing a readonly struct's field for mutation throws an AccessViolation error.

readonly struct Point { public int x; public int y; public Point(int vx, int vy) { this.x = vx; this.y = vy; } }
// Constructor can set readonly fields var p = new Point(1, 2); // Mutation outside constructor is rejected // p.x = 10; // AccessViolation // with expression bypasses readonly restriction var p2 = p with { x = 99 };
struct Value type with fields, methods, and operator overloads

Structs are value types assigned and passed by value (copy). Supports fields, methods, constructors, and operator overloads (same syntax as classes: Point operator +(Point other)).

struct Name { /* fields, methods, operators */ }
struct Rect { public int W; public int H; } var r = new Rect(10, 20); print(r.W); // 10 // Operator overload example struct Point { public int X; public int Y; public Point operator +(Point other) { return new Point(this.X + other.X, this.Y + other.Y); } }

Callables take the same argument forms as a class. A struct constructor and a struct method accept defaults, a params tail, and ref/out parameters, under the same keyword rules described for ref and out. A bare field name inside a struct method or constructor writes that instance field, exactly as it does inside a class method.

auto-properties Declare fields with automatic get/set/init accessors via { get; set; } syntax

Auto-properties combine a field declaration with automatic accessor methods. The compiler generates a hidden backing field (<Name>k__BackingField) and redirects reads/writes through the accessors. Supported on both classes and structs.

Type Name { get; set; } // public read/write Type Name { get; private set; } // public read, private write Type Name { get; init; } // public read, init-only write
// Full public read/write class Person { public string Name { get; set; } public int Age { get; set; } constructor(string n, int a) { this.Name = n; this.Age = a; } } var p = new Person("Alice", 30); print(p.Name); // Alice p.Age = 31; // public set // Read public, write private class Counter { public int Value { get; private set; } constructor(int v) { this.Value = v; } public void Increment() { this.Value = this.Value + 1; } } var c = new Counter(10); print(c.Value); // 10 (public get) // c.Value = 5; // runtime error (private set) c.Increment(); print(c.Value); // 11 (class method can write) // Init-only immutable after construction class Config { public string Name { get; init; } public int Version { get; init; } constructor(string n, int v) { this.Name = n; this.Version = v; } } var cfg = new Config("app", 1); // cfg.Name = "other"; // runtime error: init-only

Accessor modifiers: Each accessor can optionally carry its own access modifier (public, private, protected, internal). The getter must be at least as accessible as the property itself. Example: public int Id { get; private set; }.

Init vs set: init is a write-once accessor that can only be called during the initialization phase (inside a constructor or an object initializer). After construction, any attempt to write to an init-only property throws AccessViolation. Structs also support init with the same guard.

Regular fields vs properties: Both can coexist in the same class/struct. Properties expose a backing field through accessor syntax; regular fields (like public int X;) are direct storage with no accessor layer.

get / set / init The three property accessors, and who may write

A property's accessors say who may read and who may write: { get; set; } is read-write from anywhere, { get; private set; } is read from outside and written inside the class (a constructor, a method), { get; init; } is written only while the instance is being built (an object initializer or a constructor) and a later write is refused as init-only, and { get; } has no setter at all, so the object initializer is the only moment it takes a value and every later write is refused as no setter. A property here is an AUTO-property: a body is not expressible, so a computed value is a method (the auto-properties entry has that rule and the access checks).

class Settings { public int Volume { get; set; } public int Max { get; private set; } public string Name { get; init; } public int Id { get; } public constructor() { Max = 100; } } var s = new Settings() { Volume = 3, Name = "main", Id = 7 }; print(s.Volume + "/" + s.Max + "/" + s.Name + "/" + s.Id); // 3/100/main/7 // s.Name = "late"; refuses: init-only, outside initialization // s.Id = 9; refuses: the property has no setter
object initializers Initialize properties/fields at creation time via new Type { Prop = val }

Object initializers allow setting properties and fields immediately after construction using { Prop = val, ... } syntax. They work with both classes and structs, and can be combined with constructor arguments. The initialization phase sets IsInInitPhase = true so that init-only properties can be assigned.

new Type { Prop1 = val1, Prop2 = val2 } new Type(ctorArgs) { Prop = val }
// Basic object initializer no constructor args class Point { public int X { get; set; } public int Y { get; set; } } var p = new Point { X = 3, Y = 4 }; print(p.X); // 3 // Constructor args + object initializer class Person { public string Name { get; set; } public int Age { get; set; } constructor(string name) { this.Name = name; } } var p2 = new Person("Alice") { Age = 30 }; print(p2.Name + " is " + p2.Age); // Alice is 30 // Init-only property via object initializer class Config { public string Key { get; init; } } var cfg = new Config { Key = "abc" }; // init allowed during init phase // cfg.Key = "xyz"; // runtime error (outside init phase) // Struct with object initializer struct Coord { public int X; public int Y; } var c = new Coord { X = 10, Y = 20 }; print(c.X); // 10 // Explicit struct/class keyword (sugar symmetric to new struct / new class) var s = new struct Coord { X = 1, Y = 2 }; var o = new class Point(3, 4) { X = 5 };

Object initializers set IsInInitPhase = true on the instance during initialization, which allows init-only properties to be assigned. After the initializer block completes, the flag is reset to false and any further write to an init property is rejected. Regular fields, public setters, and constructor arguments are all supported in the same initializer block.

this Reference to the current class/struct instance

Used inside instance methods and constructors to access fields and methods of the current object.

this.fieldName
class Person { string Name; constructor(string name) { this.Name = name; } }
super Call base class constructor or access base members

For constructor calls: super(args) must be the first statement in the derived constructor. For member access: super.method().

super(args); super.method(args);
class Base { int X; constructor(int x) { this.X = x; } } class Derived extends Base { int Y; constructor(int x, int y) { super(x); this.Y = y; } }
base Access base class members (similar to super)

Used to access methods and fields of the base class from within a derived class.

base.method(args);
class Parent { string Greet() { return "Hello"; } } class Child extends Parent { string Greet() { return base.Greet() + " world"; } } print(new Child().Greet()); // Result: Hello world
public Accessible from anywhere

Public members are accessible from any code inside the class, from derived classes, from outside code in the same file, and from importing modules.

// Public means accessible everywhere class Visible { public int X; // field: anyone can read/write public int GetX() { return this.X; } // method: anyone can call } var v = new Visible(); v.X = 42; // allowed (public field) print(v.GetX()); // allowed (public method) → 42
Top-level class declarations also support public used to export the class from a module so it's visible to import statements. Default is private for top-level declarations.
private Accessible only within the declaring class

Private members are only accessible from within the declaring class itself. Not visible to derived classes, outside code, or importing modules.

// Private field and method only visible inside the class class Bank { private int _balance; public void Deposit(int n) { _balance = _balance + n; } public int GetBalance() { return _balance; } } var b = new Bank(); // b._balance = 100; // runtime error private b.Deposit(100); print(b.GetBalance()); // 100 via public method
// Private nested class only the outer class can reference it class Outer { private class Inner { public static string Msg = "visible inside"; } public static string Read() { return Inner.Msg; } } // Outer.Inner.Msg runtime error (private nested class) print(Outer.Read()); // "visible inside" outer class can access
Default access level for class/struct members and nested types is private. Private constructors enable the singleton pattern.
protected Accessible within the class and its derived classes

Protected members are accessible from the declaring class and from any derived class. Not visible to unrelated code or global scope.

// Protected member visible in base and derived classes class Animal { protected string Name; protected string GetLabel() { return "Animal: " + this.Name; } } class Dog extends Animal { public void SetName(string n) { this.Name = n; } // allowed (protected) public string GetDogLabel() { return this.GetLabel(); } // allowed (protected) } // Animal.Name runtime error (protected from global code) var d = new Dog(); d.SetName("Rex"); print(d.GetDogLabel()); // "Animal: Rex"
internal Accessible within the same module (cross-file)

Internal members are accessible anywhere within the same module/scope including across files loaded via import. Not visible to code outside the module. Useful for sharing state between files of a multi-file script without making it fully public.

// In module_a.slc: internal int sharedCounter = 0; public void Inc() { sharedCounter = sharedCounter + 1; } // In main.slc (after import "./module_a"): // Inc(); sharedCounter = 5; // both accessible because module imported // But code from another top-level file can't see sharedCounter
internal is the default access for top-level declarations (functions, classes, variables) when no modifier is specified and the file is part of a module (import scenario). Standalone scripts treat internal the same as public since there's only one scope.
static Shared member across all instances of a class; static constructors for one-time type initialization

Static fields and methods belong to the class itself, not to any instance. Accessed via the class name: Config.AppName = "MyApp"; or Config.GetApp(). The static keyword can appear before or after the access modifier: public static int Count() and static public int Count() are both accepted.

Static constructors (static constructor() { }) run automatically once before any instance is created or any static member is accessed. They are parameterless, cannot have an access modifier, and cannot reference this. Execution follows base-to-derived order.

class Config { static string AppName; static string GetApp() { return Config.AppName; } static constructor() { Config.AppName = "MyApp"; } // runs once } print(Config.GetApp()); // MyApp
// Static method with explicit public modifier class Counter { static int Total; constructor() { Counter.Total = Counter.Total + 1; } public static int GetCount() { return Counter.Total; } } var a = new Counter(); var b = new Counter(); print(Counter.GetCount()); // 2 (shared across instances) // C#-style factory pattern with static constructor class Shape { public string Name; private constructor(string n) { this.Name = n; } static Shape RedCircle; static Shape BlueSquare; static constructor() { Shape.RedCircle = new Shape("circle"); Shape.BlueSquare = new Shape("square"); } } print(Shape.RedCircle.Name); // circle (static ctor ran before access) // Singleton pattern with lazy initialization and private constructor class Singleton { public string Name; private static Singleton _instance; private constructor(string n) { this.Name = n; } public static Singleton GetInstance(string n) { if (Singleton._instance == null) Singleton._instance = new Singleton(n); return Singleton._instance; } } var s1 = Singleton.GetInstance("first"); var s2 = Singleton.GetInstance("second"); print(s1 == s2); // true same instance print(s1.Name); // "first" second call ignored

Rules:

  • Static members are accessed via the class name, not an instance variable
  • Static methods can only access static fields and other static methods directly
  • Static constructors run automatically once before first instance creation or first static member access
  • Static constructors are parameterless and cannot have access modifiers
  • Static constructors cannot use this there's no instance at that point
  • Base class static constructors run before derived class ones
  • Generic classes have per-concrete-type statics: Tracker<int>.Count and Tracker<string>.Count are independent
  • The class name resolves to the open generic inside the class body, so Tracker.Count works in class Tracker<T>
  • Singleton pattern: Combine private constructor with a private static field and a public static GetInstance() method. Static fields initially null for reference types are correctly resolved.

Static-only classes & structs:

  • The language does not support a static class modifier. Any class or struct can contain static members alongside instance members. A class with only static members can still be instantiated no compile-time guard exists.
  • Structs support static fields and static methods: static int Add(int a, int b) { ... } inside a struct body is valid. Access them via the struct name: Calc.Add(3, 4).
  • Nested class hierarchies where every level only contains static members work via dotted path access: Outer.Inner.InnerName. No static keyword is needed on nested classes.
  • Static field inheritance: Reading an inherited static field (e.g., Dog.Kingdom where Kingdom is declared on Animal) walks the parent chain. Writing an inherited static field via the derived class name writes to the declaring class's field (the same shared value).
Generic Methods (<T>) Type parameters on class methods

Class methods can declare type parameters with <T> syntax. There is no hard limit the parser accepts any number of comma-separated type parameters. The interpreter supports up to 16 type parameters (matching the AotInvoker limit). Type arguments are specified explicitly at the call site.

class Wrapper { V Query<T, V>(string sql) { return Sqlite.Query<T, V>(_sqlite, _path, sql); } } var list = db.Query<Person, List<Person>>("SELECT * FROM people");

Type arguments propagate through nested method calls via AST substitution. When Query<T> calls Sqlite.Query<T>(...), T is replaced with the concrete type.

A .NET generic method is closed the same way: Array.Empty<int>() instantiates Empty<int> instead of reporting the definition as unusable, and the name resolves exactly as it does for is so Array.Empty<ComNode>() is ComNode[], not object[]. A name the engine does not know is refused. Compiled bodies carry the type arguments in the bytecode, so these calls work inside a function too, not only at the top level.

On the NativeAOT build the runtime can only instantiate a generic method whose instantiation the AOT compiler already generated. A reference type (a class, string) always works; for a value type the engine ROOTS the ones a script plausibly asks for int, long, double, bool, DateTime, TimeSpan, Guid so Array.Empty<DateTime>() does close on the shipping build. A value type outside that list (Array.Empty<decimal>()) is reported by name instead of running, and never substituted. The JIT build has every instantiation.

▼ Error Handling

try/catch/finally Structured exception handling

Catches both script exceptions and .NET runtime exceptions. The finally block always runs.

A refusal names the statement it happened in, whether that statement ran compiled or on the tree walker, so a message reads the same either way: ex.Message ends with (at line L, column C), where the column is the statement's own, not the column of the operator or member that failed. The message text itself names what failed (Division by zero, Method 'Nope' not found on type string with 0 argument(s)).

A thrown value is always an ErrorInfo, whatever was thrown, so a typed clause is matched against that wrapper rather than against the value: catch (int ex) never matches a thrown 42, while catch (ErrorInfo ex) and catch (var ex) match everything. Read the value in ex.Message. Two spellings therefore catch everything (catch (var ex) and catch { }, and so does catch (ErrorInfo ex)), and a clause written after any of them can never run: that is a compile error here rather than a silent dead arm.

try { /* code */ } catch (var ex) { /* handle */ } finally { /* cleanup */ }
try { var z = 0; var crash = 10 / z; } catch (var ex) { print("caught: " + ex.Message); // Result: caught: Division by zero }
// ⚡ Super power: finally runs before return int testFinallyReturn() { try { return 42; } finally { print("Finally runs before return, value is: " + return.Value); } } print(testFinallyReturn()); // "Finally runs before return, value is: 42" then "42"
throw Throw a script exception

Throws a ScriptException with the given message, caught by the nearest try/catch.

throw "error message";
try { throw "something went wrong"; } catch (var ex) { print(ex.Message); // Result: something went wrong }
ErrorInfo Error information object caught by catch

When a catch block catches an error, the caught value is an ErrorInfo value. It provides programmatic access to the error code and message. Can be serialized via Json.Serialize().

Properties

.MessageThe error message string. For a throw "msg", this is the thrown string. For a .NET exception, the .Message property of the original exception.
.CodeErrorCode enum value programmatic category of the error (Success, InvalidOperation, IOError, etc.).
.FramesThe script frames the error unwound through, innermost first, at most 16. Each reads Inner [L12:C5]: the function, then the position it was entered at (an engine-invoked body such as a Com.Run callback has no script call site, so its frame carries the declaration's position). Empty for an error raised at the top level.
.ToString()Returns the Message string.

Example

try { throw "my custom error"; } catch (var ex) { print(ex.Message); // "my custom error" print(ex.Code); // InvalidOperation print(Json.Serialize(ex)); // {"Code":"InvalidOperation","Message":"my custom error"} }
You can match on ex.Code to differentiate error types programmatically: if (ex.Code == ErrorCode.IOError). The ErrorCode enum includes: Success, InvalidOperation, IOError, AccessViolation, DivideByZero, Overflow, SyntaxError, and others.

▼ Operators

and / or / not Pattern combinators, not boolean operators

and, or and not combine PATTERNS: x is int and > 3 is one pattern that needs both sides, x is string or int matches either, and not negates a pattern (x is not string) or makes the null check is not null. They are keywords, so they are also unusable as names. For boolean LOGIC write &&, || and !: the words do not stand in for those, which surprises a reader arriving from Python or VB. The is and match entries have the pattern rules.

object o = 7; print(o is int and > 5); // True print(o is string or int); // True print(o is not string); // True print(o is not null); // True print(true && false); // False, the BOOLEAN operator
is Type check operator

Returns true if the value is of the specified type. Supports all primitive types (int, long, short, ushort, byte, sbyte, uint, ulong, float, double, decimal, bool, char, string), named C# types (Array, List, IScriptList, IScriptDictionary), delegates, and script classes.

value is TypeName
if (x is int) { print("x is an int"); } if (x is string) { print("x is a string"); } if (fn is Func<int,int>) { print("fn is a Func"); } if (new List<int>() is List) { print("a typed list is a List"); } if (new int[3] is Array) { print("array is Array"); }

Patterns after is the same grammar switch uses: constants (x is 2), relational (x is > 5), is not <pattern>, logical (x is int and > 3), property (p is { Name: "bob" }) and list (a is [1, ..]) patterns, plus types (x is int, x is int n) and tuple patterns. List and tuple patterns also accept strings, whose elements are chars ("abc" is ['a', ..]), and a .. var rest capture follows the subject kind (a List for a list, char[] for a string, an array for arrays/tuples). Names bind only in an if/while true branch.

Patterns run on the bytecode VM, not only on the tree walker, so a handler or a parser that tests a shape keeps the fast path: the emitters are the ones a switch arm already uses, which is why the two spellings cannot disagree. Measured on a body using all of them: VM: 9 (100.0%) | Tree: 0. Two rules a reader needs: a pattern that BINDS names (other than the inline x is int n form, which binds anywhere) is allowed only in an if/while/for condition and is refused by name elsewhere (Pattern variable 'n' is only allowed in if/while conditions.), and the same body also runs correctly in a --no-source bundle, because a pattern that needs the engine's matcher travels as its own source text.

Type-qualified property patterns test a type AND its members in one pattern, which is what a factory or a dispatcher wants: o is Shape { Sides: 4 }, and negated, o is not Shape { Sides: 3 }. It is a type test combined with a property test, so it reports false for a different class that happens to hold the same member. Combinators compose with everything above, so v is null or int, s is not null and not string and n is int and > 10 and < 100 all read the way &&/|| would, with one rule from C#: not binds tighter than and/or, so s is not null and not string is (not null) and (not string). The same grammar is the match/switch arm grammar, so o match { Shape { Sides: 4 } => "four", _ => "?" } works and means the same thing.

Positional tuple patterns match a tuple, array or list element by element:

value is ("bird", 10, false)
if (v is ("bird", 10, false)) { print("bird, 10, false"); } if (p is (int x, int y, _)) { print(x + "," + y); } // literals compare with engine equality (10 matches 10.0); typed elements are exact // (use string?/int? to match null); arrays/lists match positionally; arity or // non-positional subjects are simply false. Named variables bind only inside the // if/while true branch.

Every type name is / as accepts, grouped, with what each one matches and what typeof() reports for a matching value. Matching is case-sensitive, C#-strict: a name is accepted exactly as the table spells it, so x is DateTime works and x is datetime is reported as an unknown type. Only the REPL's .lax mode matches any case. A written type's shape and arguments are part of the match: x is int[] is true for an int[] and false for a string; xs is List<int> is false for a list of strings; and as matches by these same rules, with one addition: a NUMERIC target CASTS the value to that type instead of only testing it, so 42L as int is an int and (2 << 3) as ulong is a ulong (the as entry carries the whole table). The typeof() column is what is reports for a matching value, which keeps its own type; the result of an as on a numeric target is always the TARGET's type. is function, and the engine's internal storage name for a callable, remain runtime errors, so the callable contract is Function.

Name(s) in is / asMatchestypeof() returns
Primitives and their .NET aliases numeric widening applies both ways
string / Stringa string"string"
char / Chara char"char"
bool / Booleana bool"bool"
int / Int32an int, or a long (widening)"int" / "long"
long / Int64a long, or an int (widening)"long" / "int"
byte / Bytea byte, or a long / int"byte"
sbyte / SBytean sbyte, or a long / int"sbyte"
short / Int16a short, or a long / int"short"
ushort / UInt16a ushort, or a long / int"ushort"
uint / UInt32a uint, an int, or a long"uint"
ulong / UInt64a ulong, or a long"ulong"
float / Singlea float, a double, an int, or a long"float"
double / Doublea double, a float, an int, or a long"double"
decimal / Decimala decimal"decimal"
object / Objectanything always trueany name
DateTimea DateTime"DateTime"
DateTimeOffseta DateTimeOffset"DateTimeOffset"
TimeSpana TimeSpan"TimeSpan"
Enumany .NET enum value (ConsoleColor.Red, TaskStatus.Completed)the enum's own name
Collections and their interfaces
Lista script list: new List<int>(), a .ToList(), a comprehension"List" / "List<int>"
Dictionarya script dictionary: a dict literal or a parsed JSON object"Dictionary" / "Dictionary<string, int>"
IDictionarya raw .NET dictionary only a script dict is a Dictionary, so d is IDictionary is False"Dictionary"
HashSeta script set"HashSet" / "HashSet<int>"
Arrayany native array [1,2,3], new int[3], new object[2]"int[]" / "object[]"
Tuplea tuple"Tuple"
KeyValuePairone pair from iterating a dictionary"KeyValuePair"
LazyDeserializedLista list produced by a typed Json.Deserializethe declaration the read was asked for, List<int> or string[] or IList
OrderedEnumerablea LINQ OrderBy / ThenBy result"OrderedEnumerable"
ReplayableEnumerableReplayable() / Memoize()"ReplayableEnumerable"
LazyEnumerableIterable.Map / Filter / Zip / Append / Range"LazyEnumerable"
Contracts a guard, not a name typeof() gives up
Iterablearrays, lists, tuples, dicts, HashSets, LINQ results, generators, stringsthe concrete name (int[], List<int>…)
RandomAccessarrays, lists, tuples, strings indexable and re-enumerablethe concrete name
Functionany callable: lambda, named function, bound method, combined delegate, native"Function"
Class / ClassInstance / class instancea class or record instancethe declared class name, e.g. "Animal"
Struct / StructInstance / struct instancea struct instancethe declared struct name, e.g. "Pt"
ClassInfoa class / record / struct / enum name used as a value, or a generic type reference such as Dictionary<string, object>the declared name ("Animal", "Pt", "Color"), or the whole spelling ("List<int>")
Delegate / Func / Action / Predicatea .NET delegate not a script lambda (that is Function)the delegate's own type name
Resultwhat RunScript() returns"Result"
ErrorInfoa caught error"ErrorInfo"
Coroutinea coroutine / generator"Coroutine"
EventInfo / eventan event"EventInfo"
CombinedDelegate / delegatethe result of f1 + f2"CombinedDelegate"
DelegateInfo / delegate typea declared delegate type"DelegateInfo"
Namespacea namespace object: Json, Iterable, the Win32 namespace…"Namespace"
Nativea native such as print"Native"
VoidMarker / voidthe result of a call that returns nothing"void"
MemBuffera Mem.Buffer"MemBuffer"
RefCella by-reference cell bound to a caller's slot"RefCell"
WeakRefa weak reference"WeakRef"
Regexa compiled regular expression"Regex"
CronExpressiona parsed cron schedule"CronExpression"
CronTypeits schedule-type enum"CronType"
Runtime types the interpreter hands out
Metaa loaded bytecode bundle's metadata"Meta"
DynamicLibrarya LoadLibrary handle"DynamicLibrary"
FileStreamReader / FileStreamWriterstream wrappersthe same names
MessageInfo / CipherInfoa parsed message / a cipher handlethe same names
SqliteIterator / SqliteMappingIterator / SqliteRowdatabase iteration and a mapped rowthe same names
Nativea resolved native entry point"Native"
TaskTask.Run / Task.Delay"Task"
ScheduledTaskwhat Scheduler.Add / Enqueue / Schedule returns"ScheduledTask"
SleepRequest / EventWaitRequest / HttpRequest / ReadLineRequestthe yield requests Coroutine.Sleep / Wait / Fetch / ReadLine returnthe same names
Types the interpreter's own surfaces hand out: UI, SQLite, COM and the Win32 API
Button / ButtonBase / CheckBox / ComboBox / DateTimePicker / GenericControl / Label / ListBox / ListView / NativeApp / OpenFileDialog / RadioButton / Rebar / SaveFileDialog / StatusBar / SysLink / TabControl / TextBox / TheTimer / ToolBar / TrackBar / TreeViewa UI object of that kind, from the Application / Form surfacethe name as spelled
KeyEventArgs / MouseEventArgs / MouseButtons / KeyCodes / HotKey / ItemsCollection / ControlCollectionan event argument, a key or mouse code, or a control's child collectionthe name as spelled
ComObject / ComScope / ComNodea COM object, scope or node from Com.CreateObject / GetObjectthe name as spelled
.NET and system types bound in scope
Console / ConsoleColor / Convert / Directory / DockStyle / Encoding / Environment / File / FileAttributes / GC / Guid / Math / Path / Rect / RegexOptions / Size / StringBuilder / TimeZoneInfo / ClientStatus / CoroutineStatus / TaskStatus / CancelEventArgs / EventArgs / CancellationToken / CancellationTokenSource / Control / Form / MdiChild / MdiForman instance of that type Guid.Empty is Guid, Encoding.UTF8 is Encoding, ConsoleColor.Red is ConsoleColor, DockStyle.Bottom is DockStyle. The static-only names (Console, Convert, Directory, Environment, File, GC, Math, Path) never match a value: is Math is a legal False, not an unknown name.the name as spelled ("Guid", "Rect", "ConsoleColor"…)

The callable contract is Function; the engine's internal storage name for that type is NOT exposed to scripts, so writing it is a runtime error (unknown or undefined type).

When adding a new internal type, give its name a Type in ScriptTypeRegistry (TypeAliases.cs). A contract (a predicate over several types, like Iterable, RandomAccess or Function) needs an arm in TryMatchKnownType (VisitExpressions.cs) instead. crash_typeof_matrix.slc asserts both halves.

The registry entry is not the same thing as binding the name in scope, and a type a VALUE can be written back as needs both. The is / as default arm reads ScriptTypeRegistry directly, while typename() and the bare-identifier fallback go through ResolveTypeToClr (that table, then a global-scope Type, then the CLR's own lookup). Measured: with DockStyle bound in the global scope alone, DockStyle.Bottom worked and typeof(bar.Dock) already answered "DockStyle", while bar.Dock is DockStyle was a silent False (the failure shape the is switch's default arm was written to stop producing). One entry in the registry is what makes the name a script can WRITE agree with the name a value REPORTS.

as Type cast operator (returns null on failure)

Safe cast: returns null where a direct cast (T)value would refuse, instead of throwing. A numeric target is a real cast: the answer carries the TARGET's type and converts exactly as (T)value does (truncation, unchecked wrapping, C#'s rounding). So (2 << 3) as long is a long, (2 << 3) as byte is a byte and (2 << 3) as ulong is a ulong, where the type-test reading answered an int or null. The numeric family is the eleven numeric types plus char, and char is a code point both ways (65 as char is 'A', 'A' as int is 65). For every OTHER target as is a type test that never converts: a number is not a string (42 as string is null), a string is never parsed into a number ("42" as int is null), and a bool is not part of the numeric family (true as int is null while (int)true is 1). Supports all primitive types (int, long, short, ushort, byte, sbyte, uint, ulong, float, double, decimal, bool, char, string), named C# types (Array, List, IScriptList, IScriptDictionary), delegates, and script classes.

value as TypeName
var fn = fun(int x) { return x * x; }; var casted = fn as Func<int,int>; if (casted is not null) { print(casted(21)); } // Primitive examples all numeric types support cast var v1 = 42 as int; // 42 var v2 = 42 as long; // 42 var v3 = 42L as long; // 42 var v4 = 42f as float; // 42.0 var v5 = 3.14m as decimal; // 3.14 var v6 = (short)100 as short; // 100 var v7 = (byte)255 as byte; // 255 // Collection types var lst = new List<int>() as List; var arr = new int[3] as Array; // Returns null on mismatch var bad = 42 as string; // null // A NUMERIC target CASTS, so the answer carries the target's type and converts as (T)value does var n1 = (2 << 3) as long; // long 16 (not an int) var n2 = (2 << 3) as uint; // uint 16 var n3 = (2 << 3) as ulong; // ulong 16 (not null) var n4 = (2 << 3) as byte; // byte 16 var n5 = 300 as byte; // byte 44, the same wrap (byte)300 gives var n6 = 3.9 as int; // int 4, the same rounding (int)3.9 gives var n7 = 1e300 as decimal; // null, where (decimal)1e300 refuses

Every numeric case, next to the direct cast it mirrors. Both columns are the same conversion; only the failure differs, because the cast throws and as answers null.

ExpressionResult (and its typeof)
(2 << 3) as longlong 16
(2 << 3) as uintuint 16
(2 << 3) as ulongulong 16
(2 << 3) as bytebyte 16
300 as bytebyte 44, wrapping exactly as (byte)300
-1 as uintuint 4294967295, as (uint)(-1)
3.9 as intint 4, the same rounding as (int)3.9
65 as charchar 'A'; 'A' as int is 65
1e300 as decimalnull, where (decimal)1e300 refuses
"42" as intnull: a safe cast never parses text, while (int)"42" is 42
true as intnull: a bool is not numeric, while (int)true is 1
42 as stringnull: the target is not numeric, so only the type test runs
is not null Non-null check pattern

Pattern matching syntax for null checks. Returns true when the value is not null.

value is not null
var maybeFunc = fn as Func<int,int>; if (maybeFunc is not null) { print("result: " + maybeFunc(42)); }
ternary (?:) Conditional expression operator

Returns trueValue if condition is truthy, falseValue otherwise.

condition ? trueValue : falseValue
var label = (x > 0) ? "positive" : "non-positive";
with Non-destructive copy of a struct or class with field overrides expr with { field = value, ... }

The with expression creates a deep copy of a struct or class instance, applying specified field overrides. The original instance is not modified. Works with readonly structs and init-only properties (bypasses mutation restrictions during the copy).

var p2 = p with { x = 99 };
// Struct copy with override struct Point { public int x; public int y; } var p = new Point(); p.x = 10; p.y = 20; var p2 = p with { x = 99 }; print(p2.x); // 99 (overridden) print(p2.y); // 20 (preserved) print(p.x); // 10 (original unchanged) // Class copy with override class Person { public string name; public int age; } var alice = new Person(); alice.name = "Alice"; alice.age = 30; var bob = alice with { name = "Bob" }; print(bob.name); // "Bob" print(bob.age); // 30 (preserved)
+ - * / % Arithmetic: add, subtract, multiply, divide, modulo

Standard arithmetic operators. Integer division truncates toward zero. Mixed numeric types promote to the wider type (int + long → long, int + double → double).

Modulo follows the same promotion: with two integers it is an integer remainder and a zero divisor throws, while a double or float operand, or a decimal paired with another type, computes in floating point (7.5 % 2 is 1.5, and a 0.0 divisor gives NaN).

Small integer promotion: sbyte, byte, short, ushort, and char are automatically widened to int before arithmetic so the result stays precise. Example: sbyte.MaxValue + 1 returns int 128 (not double).

a + b // addition a - b // subtraction a * b // multiplication a / b // division a % b // modulo (remainder)
123 + 10 = 133 123 - 10 = 113 123 * 10 = 1230 123 / 10 = 12 // integer truncation 123 % 10 = 3 // remainder 5 + 2.5 = 7.5 // int promoted to double
Division by zero throws a runtime error. Use try/catch when dividing by a variable that could be zero.
== != < > <= >= Comparison operators equality, inequality, ordering

Compare two values. == and != work on all types (including null). Ordering (<, >, <=, >=) works on numeric types and strings.

a == b // equality a != b // inequality a < b // less than a > b // greater than a <= b // less than or equal a >= b // greater than or equal
123 == 10 → false 123 != 10 → true 123 < 10 → false 123 > 10 → true
&& || ! Logical AND, OR, and NOT short-circuit evaluation

&& and || short-circuit: the right operand is only evaluated if needed. ! negates a boolean value. Any value can be used as a condition falsy values are false, null, and 0.

a && b // logical AND a || b // logical OR !a // logical NOT
if (x > 0 && x < 100) { print("in range"); } if (x == null || x == 0) { print("falsy"); } if (!done) { print("not done yet"); }
& | ^ ~ << >> Bitwise AND, OR, XOR, NOT, left shift, right shift

Bitwise operators work on integer types. ~ is the bitwise complement (one's complement). << shifts bits left (multiply by power of two), >> shifts bits right (divide by power of two).

A shift count is masked by the width of the promoted left operand, as in C#: & 31 for a 32-bit type and & 63 for a 64-bit one, so 1 << 33 is 2 and stays an int, while 1L << 33 is 8589934592 and stays a long. The result keeps the promoted operand's type, which is also why ~ and unary minus of an sbyte, byte, short or ushort answer an int.

a & b // bitwise AND a | b // bitwise OR a ^ b // bitwise XOR ~a // bitwise NOT (complement) a << b // left shift a >> b // right shift
0b1010 & 0b1100 → 8 // (0b1000) 0b1010 | 0b1100 → 14 // (0b1110) 0b1010 ^ 0b1100 → 6 // (0b0110) ~5 → -6 10 << 2 → 40 12 >> 1 → 6
= += -= *= /= %= &= |= ^= <<= >>= Assignment and compound assignment, and the order in which a target is evaluated

= stores a value and the expression is worth what it stored, so assignments chain and can be captured: a = b = 5 leaves both at 5, and var r = (k += 2) puts the new k in r.

The compound forms are += -= *= /= %= &= |= ^= <<= >>=; each reads the target, applies the operator of the same name to the given value, and stores the result. += on a string concatenates, and the arithmetic ones keep the numeric rules of + - * / %. ??= assigns only when the target is currently null (see ??=), and ++/-- are the one-step spellings (see ++ --).

The target is resolved ONCE, in C#'s order: the receiver first, then any indices from left to right, then the current value is read, then the right operand is evaluated, then the operation, then the store. So Arr()[Next()] += 5 calls the receiver once and the index once, and the read and the write land on the SAME element. Evaluating the index a second time for the write would write an element that was never read, which is the defect this order exists to prevent.

A target may be a variable, a field or a property (their access rules apply, so a private setter from outside is refused), or an array element, which is a variable. The stored value is converted to the target's declared type by the same rule every other door uses, a plain assignment included, so string[] s = ["x"]; s[0] = 42; stores "42" exactly as string a = 42; does, and a value that cannot convert is refused there with the same sentence. A List element holding a struct is not a variable: the indexer hands back a copy, so list[0].X = 1 is refused and the fix is to take the element into a variable, change it, and store it back with list[0] = item. A const cannot be assigned at all.

// the target is evaluated once, so the read and the write agree var items = [1, 2]; items[0] += 10; // items is [11, 2] // chained assignment and the value of the expression var a = 0; var b = 0; a = b = 5; // both 5 var k = 3; var r = (k += 2); // k is 5, r is 5 // += concatenates a string var s = "a"; s += "b"; // "ab"
++ -- Prefix and postfix increment/decrement

Both prefix and postfix forms are supported: ++x/--x modify the variable and return the new value; x++/x-- return the old value then modify. They work on local variables, global variables, and property/index targets (c.N++, arr[i]--). An independent member of the assignment operators, and they follow the same rule: the target is resolved ONCE (receiver, then indices), so arr[Next()]++ reads and writes the same element.

++x // increment then return new value --x // decrement then return new value x++ // return old value, then increment x-- // return old value, then decrement
var x = 10; print(++x); // Result: 11 print(--x); // Result: 10 print(x++); // Result: 10 (returns old value) print(x); // Result: 11 // On globals and members ++gCount; // prefix on a global obj.Score++; // postfix on a property arr[0]--; // postfix on an index target
?? Null-coalescing returns left side if not null, else right side

The ?? operator returns the left operand if it is not null; otherwise it evaluates and returns the right operand. Short-circuits: the right side is not evaluated if the left side is non-null.

left ?? right
var name = null ?? "default"; print(name); // "default" var x = 42; print(x ?? 99); // 42 (short-circuits, 99 not evaluated) // Chaining var result = null ?? null ?? "fallback"; print(result); // "fallback"
Short-circuit ensures the right operand is only evaluated when the left is null side effects in the right expression may not run.
Precedence is C#'s: ?? binds looser than a comparison, so x ?? "" == y parses as x ?? ("" == y) and answers its LEFT operand whenever that is not null (a truthy value) instead of comparing anything. Parenthesize the value you compare: (x ?? "") == y.
??= Null-coalescing assignment assign right side only if the target is null

The ??= operator assigns the right operand to the target only if the target is currently null; otherwise the target keeps its value and the right operand is not evaluated (short-circuit). Works on local variables, global variables, array elements, class/struct fields, and dictionary entries. It is the null-only member of the assignment operators and follows the same rule: the target is resolved ONCE, so Map()[Next()] ??= v looks the entry up one single time and either keeps it or stores into it.

target ??= value
var x = null; x ??= 5; // x was null → x = 5 x ??= 99; // x is 5 (non-null) → keeps 5, 99 NOT evaluated print(x); // 5 // Dictionary entry var cache = new Dictionary<string, object>(); cache["key"] ??= "computed"; // Array element var arr = new object[1]; arr[0] ??= 42;
Short-circuit semantics match ??: the right side is only evaluated when the target is null, so side effects in the right expression may not run. Variable targets run in the bytecode VM; array/field/dict targets use the tree interpreter.
?. Null-conditional access member only if target is not null

The ?. operator accesses a property or method only if the target is not null. Returns null if the target is null, avoiding NullReference errors. Supports property access, method calls, and chaining.

obj?.Property obj?.Method()
class Node { public Node Next; public int Id; } var n = new Node(); print(n?.Id); // 0 print(null?.Id); // null (no crash) print(n?.Next?.Id); // null (chained null-safe access)
Internally, obj?.Prop is syntactic sugar for obj != null ? obj.Prop : null. Supports arbitrary nesting: a?.b?.c?.d.

A member chain may break before the dot, as in C#. s.Replace(a, b) on one line with an indented .Replace(c, d) on the next is one expression, exactly as it is in C#; a trailing dot works the same way. The one line shape that is not a continuation is a line whose first character is a dot and whose name is a REPL command (see .help): that is a directive, and a file carrying one is stripped of it before it is read.

?. protects a READ, and it does not protect a WRITE. As an assignment target it is refused only when it is the last hop before the member being written: form[n]?.Text = "x" is a parse error, and so are form[n]?.Text += "x" and form[n]?.Text++, because a guarded write has no defined meaning here (skipping it silently would hide a name that does not resolve, which is the one thing a rebuilt name must not do). A ?. ANYWHERE ELSE in a target is IGNORED, and that is worth knowing because it reads like protection: form[n]?.Controls.Get(0).Text = "x" parses, writes the same thing as form[n].Controls.Get(0).Text = "x" when the receiver is there, and when the receiver is null it fails further out (on Get) with nothing said about the guard. Write the guard instead of spelling it: var b = form[n]; if (b != null) { b.Click = (...) => { ... }; }

.. Range operator creates an array from start to end (inclusive), or slices collections/indexers

The .. operator has two uses:

  1. Numeric range: 1..5 creates a long[] array containing all integers from left to right inclusive. Used with foreach, comprehensions, and destructuring.
  2. Slice/indexer: arr[1..4] selects a slice from index 1 (inclusive) to 4 (exclusive). Works on arrays, strings, List<T>, and any type with Length/Count. Open ends allowed: arr[..3], arr[2..], arr[..].
1..5 // → [1, 2, 3, 4, 5] (long[]) numeric range arr[1..4] // → [20, 30, 40] slice (indices 1→4 exclusive) s[0..5] // → "hello" substring (indices 0→5 exclusive) arr[..3] // → [10, 20, 30] open start (same as 0..3) arr[2..] // → [30, 40, 50] open end (same as 2..count) arr[..] // → [10, 20, 30, 40, 50] full copy
// Numeric range in foreach var sum = 0; foreach (var i in 1..100) { sum = sum + i; } // Slice an array var arr = [10, 20, 30, 40, 50]; var mid = arr[1..4]; // [20, 30, 40] // Substring var s = "hello world"; var hello = s[0..5]; // "hello" // With variables var start = 2; var end = 5; var slice = arr[start..end]; // [30, 40, 50]
For numeric ranges, left must be ≤ right, and max size is 1,000,000. For slices, indices are exclusive at the end (matching C# Range semantics). Use with ^ for from-end indexing: arr[1..^1]. Start > end produces an empty result.
^ (index from end) Hat operator index a collection from the end (^1 = last element)

The ^ operator (hat/caret) is a prefix unary operator that creates an index from end value. When used inside square brackets [...] on a collection, it computes the offset from the end using Length or Count.

Supported types: arrays, strings, List<T>, and any type with Length or Count.

arr[^1] // last element arr[^2] // second-to-last arr[^3..^1] // slice from 3rd-from-end to 1st-from-end arr[^5..] // slice from 5th-from-end to end arr[..^1] // slice from start to 1st-from-end (all but last) s[^1] // last character (as string)
var arr = [10, 20, 30, 40, 50]; print(arr[^1]); // 50 (last element) print(arr[^3..^1]); // [30, 40] // With variables var n = 2; print(arr[^n]); // 40 // Strings var s = "hello world"; print(s[^5..^1]); // "world"
^0 is always out of range (throws). For an empty collection, ^1 throws. Standalone ^ is the bitwise XOR operator from-end indexing only works inside [...].

▼ Literals & Notation

0x / 0b notation Hexadecimal (0x…) and binary (0b…) integer literals

Integers can be written in hexadecimal (0x) or binary (0b) notation. Underscores are allowed as digit separators.

0xFF // 255 hex 0b1010 // 10 binary 0xDEAD_BEEF // hex with underscore separator 0b1100_1010 // binary with separator
var hex = 0xFF; // 255 var bin = 0b1010; // 10 var mask = 0x80000000; // bitmask print(0xF & 0b0011); // Result: 3
numeric suffixes Force a specific numeric type with a suffix: L, f, d, m, u

Numeric literals can be suffixed to force a specific runtime type. Without a suffix, integer literals are int/long and float literals are double. All 11 primitive numeric types are supported via (cast) syntax in addition to suffixes.

42L // long 42f // float 42u // uint 42UL // ulong 3.14d // double 3.14m // decimal 1.5f // float (short)100 // short (via cast) (ushort)200 // ushort (via cast) (byte)255 // byte (via cast) (sbyte)-128 // sbyte (via cast)
var x = 42L; // long var y = 42f; // float var z = 3.14m; // decimal var w = 42 as long; // safe cast at runtime
scientific notation (e/E) Floating-point literals in scientific notation: 1e30, 2.5e-3, 1E2

Numeric literals can use e or E for scientific (exponential) notation. The result is always double unless a suffix (m, d, f) is present. An optional + or - sign may follow the exponent character.

1e30 // double (1 × 10³⁰) 2.5e-3 // double (2.5 × 10⁻³ = 0.0025) 3.14e+2 // double (3.14 × 10² = 314) 1E2 // double (100) 1e5m // decimal (via m suffix) 2.5e-2d // double (via d suffix)
double big = 1e30; // large positive double tiny = 1e-10; // small positive double val = 2E5; // 200000 decimal dec = 1e3m; // 1000 (decimal) var sum = 1e10 + 1e10; // 2e10 (double)
true / false The two boolean literals

The boolean literals are true and false, the two values of bool. They are KEYWORDS, so they are case-sensitive: True and False are undefined names rather than booleans, and that spelling is worth knowing because VBA, PowerShell and C# all write it with a capital (it silently disabled a COM release recipe in this repository for a day). Use &&, || and ! for logic; the words and, or and not combine PATTERNS.

var ok = true; var no = false; print(ok ? "yes" : "no"); // yes print(no || ok); // True print(1 < 2 && ok); // True // True is an undefined name, not a boolean: write true
raw strings (""") Multi-line verbatim string literals delimited by triple quotes no escape sequences

A raw string literal is delimited by three double quotes (""") and spans multiple lines. The content is taken verbatim: no escape sequences are processed (\n stays as backslash-n), quotes are allowed inside, and the first line break right after the opening """ is skipped (C# semantics). Ideal for embedded SQL, JSON, HTML, or regex.

The delimiter is a run of three or MORE quotes, and the literal closes on a run of the same length: """"abc"""" is abc, and a wider opening is what lets the content hold a run of quotes ("""""ab""c""""" is ab""c). A longer run than the delimiter is refused, which is C#'s own rule (CS8998): """abc"""" cannot be a raw string, so a single-line raw string may never end with a quote. Two fixes, and the refusal names both: put a space before the closing quotes ("""... "%TEMP%/empty-tools" """), or write it multi-line with the closing delimiter on its own line, where a trailing quote is fine because a line break separates it from the delimiter.

A string that holds double quotes needs neither this nor \": single quotes hold them directly, so 'say "hi"' is the short spelling (a single-quoted literal is a string, not only a char, and it still processes escapes: 'x\ny' is three characters). Reach for a raw string when the text spans lines or holds an apostrophe as well. A raw string can also be interpolated: $"""...{expr}...""" fills holes in verbatim text, and each extra $ makes a hole one more brace, so $$"""...{{expr}}...""" leaves every single brace alone, which is what a template holding CSS or JSON wants. See string interpolation for the forms and for what a brace means in each.

A MULTI-LINE literal is trimmed exactly the way C# trims it, which is what lets a template be indented in the source. Three rules, and the value of """, newline, abc, newline, """ is abc: the line break right after the opening quotes is skipped, the break before the closing quotes is dropped with the indentation that precedes them, and that same indentation is removed from the start of every content line (a line left with only whitespace loses it). So a template written at a method's indentation arrives unindented, and the indentation of the closing """ is the number it strips: put the closing quotes at column 1 and nothing is stripped, which is how a literal keeps leading spaces on purpose. A one-line raw string is never trimmed.

var sql = """SELECT id, name FROM users WHERE id = 5""";
// Multi-line SQL (first newline after """ is skipped) var query = """SELECT id as Id, name as Name, cron_expr as CronExpr FROM scheduled_tasks ORDER BY Id"""; // JSON with embedded quotes no escaping needed var payload = """{ "name": "Alice", "tags": ["a", "b"] }"""; var parsed = Json.Parse(payload); // Backslashes stay literal (no escape processing) var path = """C:\Users\data\file.txt"""; // backslashes preserved
Raw strings are a lexer-only feature the token is produced directly with no interpolation or escape processing. For interpolated raw strings, see the string interpolation entry ($@"..." verbatim interpolation).

▼ Delegates

delegate Declare a delegate type

Delegates define a type-safe function pointer signature. They can be declared at top level or inside a class body.

delegate ReturnType TypeName(params);
delegate int IntOp(int x); var fn = fun (int x) => x * 2; var op = fn as IntOp; print(op(5)); // 10
Inside a class body, delegate declarations can have access modifiers: public delegate, private delegate, protected delegate, internal delegate. Default is public.
event Event declaration (observer pattern)

Events are multi-cast multiple subscribers can be added via += and removed via -=. Supported in classes.

event DelegateType EventName;
class Button { delegate void ClickHandler(int x); event ClickHandler OnClick; void Press() { this.OnClick(1); } } var btn = new Button(); btn.OnClick += fun (int n) { print("clicked " + n); }; btn.Press(); // Result: clicked 1
Events support access modifiers inside classes: public (default), private, protected, internal. Private/protected events are accessible through public methods of the class.
Action<> Void-returning delegate with 0-4 parameters

Built-in generic delegate types: Action, Action<T>, Action<T1,T2>, etc.

Action Action<T> Action<T1, T2>
Func<> Delegate with return value, 0-4 parameters

Built-in generic delegate types: Func<TResult>, Func<T,TResult>, etc.

Func<TResult> Func<T, TResult> Func<T1, T2, TResult>

▼ Modules

import Load another script file as a module

Imports can be aliased (import "path" alias Name) or merged directly into the current scope. Circular imports are detected and handled. Since the bytecode-library work, import also works as a statement inside blocks (function bodies, try blocks, etc.), not only at top level.

A module is namespace-isolated and that has two limits. Its FUNCTIONS and CLASSES arrive as exports, but an extension block declared in it does NOT register in the importer, and neither does a struct. An imported extension(string) member answered Method 'XlIsLegalSheetName' not found on type String, and an imported struct name was Type 'XlSheetRef' not defined in the importer while a class from the same file worked. Co-locate an extension block, and any struct it mentions, with the file that uses them.
An import binds the imported names read-only and nothing else. A flat (non-aliased) import defines each exported symbol as a constant of the importing scope, so assigning to one throws ConstAssignment: import "./lib.inc"; followed by plain = 1 fails when the module exports plain. Your own variables are not affected, single-letter ones included var i = 1; after an import is still assignable. (Until it was fixed, the constant check compared by substring rather than set membership, so an import made every name that merely occurred inside an imported one read-only: i was unassignable after import "…/_ns_decl_lib.inc" it occurs inside Include while zz worked. If you read a report of that behaviour, it was the bug, not the rule.)
import "path/to/script.slc" [alias Name] import "path/to/lib.slcbc" as Name // bytecode library (alias required) import Application.Path + "/m.inc" as Name // the path may be an EXPRESSION import $"{Script.Directory()}/m.inc" as Name
The path can be computed, which is what a deployed script needs. A literal is the common case, but any expression that yields a string works, and it is evaluated WHERE THE IMPORT RUNS: import Application.Path + "/_m.inc" as Z;, import $"{dir}/_m.inc" as Z;, or a path held in a variable. That is how a module beside the executable is reached at all, since its directory is only known at run time; Script.Directory() is the module beside the script and Application.Path the one beside the .exe. The value must be a non-empty string, and anything else is refused by name (The import path must be a string, not 'int'). In an import, as introduces the ALIAS rather than a cast, so expression as Z binds Z as it reads. ONE limit follows from the path being a run-time value: a computed path cannot be carried as load-time data, so a bundle re-runs the import at its own position when the program runs, while a declaration-only load (.loadslcbc, Bytecode.LoadScript) binds no names for it. Use a literal when the file is meant to be loaded that way.
An import path is a SEARCH, so a module is found from wherever the script is run. The general path rule is tried first ("./x" is beside the run, any other relative spelling against the process directory), so nothing that resolved before changes. When that finds nothing, the run's own directory is tried, then each of its ancestors, nearest first. That is what makes a file runnable from its own directory: import "_m.inc" finds the module beside the script, and import "assets/lib/_m.inc" finds it at the repository root whether the run started there, in the deployed copy beside the executable, or in the script's own folder. Only an import searches this way; File and Directory keep the single rule, because a data path is not a dependency to look for.
A module's own functions see what its own imports brought in, and the namespace they bring in is a NAME a function can read. A flat import binds each exported name, and a module declared with namespace A.B { … } arrives as a namespace you reach by that name (A.B.member). A function declared in the same module resolves both, so namespace Outer { int call(int n) { return Shared.Include.add(n, n); } } works in a file that imported Shared, whichever engine runs the top level. That resolution is the engine's single global read, the same one a compiled body uses, so a name a top-level import bound is found from a function body too.
// Import as alias import "assets/lib/math.slc" alias Math; print(Math.PI); // Result: 3.14159 // Import directly into scope import "assets/language/repl/core/animal_module.slc"; var a = new Animal("cat"); // Import a bytecode library (compiled with Bytecode.ExportLibrary) as a namespace import "lib.slcbc" as Z; print(Z.Math.add(2, 3)); // 5 a namespaced function is Z.ns.fn print(Z.add(2, 3)); // 5 a flat function is Z.fn print(Z.__meta.Name); // library metadata (name/version/description/sources) // import also works inside blocks void setup() { import "lib.slcbc" as Lib; // alias is block-scoped print(Lib.mul(6, 7)); // 42 }
Bytecode libraries (.slcbc): a file produced by Bytecode.ExportLibrary(out, meta, scripts... or (script, ns) tuples...) bundles the VM-compiled top-level functions of several scripts. Each exported script can declare a symbolic namespace via a (script, ns) tuple import "lib.slcbc" as Z then exposes Z.ns.fn(...) (flat Z.fn(...) when the namespace is empty); ns may be dotted ("A.B" → Z.A.B.fn). Import it with an alias (import "lib.slcbc" as Z) a bare bytecode-library import is an error. Non-VM-compiled functions are skipped at export (a plain value-yield coroutine does compile and is exported; a coroutine that requests a yield is not). Top-level variables are included as value snapshots; an unserializable one aborts the export (ScriptException naming the variable, before the file is written) unless it is explicitly listed in a trailing ignoreVars array/list argument those names are skipped with a warning. See the Bytecode entry. Compiled libraries can also be merged with Bytecode.MergeLibrary(out, meta, libs...) functions keep their namespaces, and the caller-supplied meta becomes the merged library's __meta.
namespace Declare a nested namespace; organize functions, classes and delegates under a dotted path

A namespace groups top-level functions, classes, structs, delegates and variables under a dotted path (A.B.C). Declared namespaces are organizational in the declaring file (members stay callable flat and qualified) and become a real nested path when the file is imported: with an alias they nest under the alias root (Z.A.B.fn), without an alias they nest into the importer's own scope (A.B.fn). Imports of namespaced modules also work as statements inside blocks.

namespace A.B.C { /* members */ } // block form namespace A.B.C; // file-level form: following top-level members nest

1 · Basic declare and import

// lib.slc declare a nested namespace (block form, dotted path) namespace My.Include { int add(int a, int b) { return a + b; } namespace Deep { // a namespace block may nest inside another string greet(string who) { return "Hello, " + who; } } internal class Calc { public int Mul; public Calc(int x) { this.Mul = x * 2; } } } int plain(int x) { return x + 1; } // a flat member outside any namespace // inside the declaring file, members are reachable BOTH flat and qualified print(add(2, 3)); // 5 flat print(My.Include.add(2, 3)); // 5 in-file qualified access print(My.Include.Deep.greet("a")); // Hello, a nested path print(new Calc(5).Mul); // 10 classes stay flat in the declaring file print(new My.Include.Calc(5).Mul); // 10 and qualified
// main.slc import a namespaced module import "lib.slc" as Z; // alias → declared paths nest under the alias root print(Z.My.Include.add(2, 3)); // 5 print(Z.My.Include.Deep.greet("bob")); // Hello, bob print(new Z.My.Include.Calc(5).Mul); // 10 namespaced class via its qualified name print(Z.plain(41)); // 42 flat members stay on the alias root import "lib.slc"; // no alias → nests into the importer scope print(My.Include.add(4, 5)); // 9 print(plain(9)); // 10 flat member callable bare too

2 · Advanced builtins, chained imports, bytecode

// Extend a builtin namespace copy-on-write, other interpreters are unaffected namespace Json { int answer() { return 42; } } // merges into a private copy of the builtin print(Json.answer()); // 42 new member print(Json.Parse("7")); // 7 the original builtin members are still there // A fresh interpreter (RunScript) has no Json.answer the extension is per-interpreter. // Script-facing builtins are re-exported through imports: // ext_json.slc declares: namespace Json { int answer() { return 42; } } import "ext_json.slc" as E; print(typeof(E.Json)); // namespace the alias reaches the (extended) builtin print(E.Json.answer()); // 42 re-exported extension print(E.Json.Parse("1")); // 1 original builtin methods ride along through the alias
// Chained imports a module that imports the namespaced lib re-exports its namespaces // outer.slc: import "lib.slc"; namespace Outer { int callInner(int n) { return My.Include.add(n, n); } } import "outer.slc" as W; print(W.Outer.callInner(3)); // 6 the outer fn calls the inner module via its scope print(W.My.Include.add(1, 2)); // 3 inner namespaces re-export through the chain
// Bytecode (.slcbc) round trip declared namespaces are preserved at export and import Bytecode.ExportLibrary("lib.slcbc", Bytecode.Meta("Lib", "1"), ("lib.slc", "")); // empty tuple ns → declared paths win, flat stays flat import "lib.slcbc" as B; print(B.My.Include.add(2, 3)); // 5 print(B.My.Include.Deep.greet("z")); // Hello, z print(B.plain(41)); // 42 flat member stays flat in the bundle // Bare sibling calls resolve from the bundle via the function's namespace. // lib.slc additionally declares: // namespace My { int callFlat(int n){ return plain(n); } // nested → FLAT sibling // namespace Deep { int callUp(int n){ return add(n,n); } } // deeper → ancestor // int add(int a, int b){ return a+b; } } print(B.My.Deep.callUp(21)); // 42 deeper → ancestor sibling (B.My.add) print(B.My.callFlat(41)); // 42 nested → flat sibling at the root (B.plain)
// Alias-qualified bundle classes same bare name, different namespaces, coexist import "geoA.slcbc" as PA; // geoA.slcbc exports class Point under namespace GeoA import "geoB.slcbc" as PB; // geoB.slcbc exports class Point under namespace GeoB var pa = new PA.GeoA.Point(3); var pb = new PB.GeoB.Point(5); print(pa.X, pb.Y); // 3 5 both registered under their own aliases print(Point == PA.GeoA.Point); // True bare `Point` is first-wins (GeoA)

3 · Edge cases

// Namespace-declared coroutines work direct generator call, args preserved namespace Coro { int pairs(int n) { var i = 0; while (i < n) { yield (i, i * 2); i = i + 1; } return -1; } } var gen = Coro.pairs(2); // in-file qualified access to a namespaced coroutine print(gen.MoveNext(), gen.Current[0], gen.Current[1]); // True 0 0 print(gen.MoveNext(), gen.Current[0], gen.Current[1]); // True 1 2 print(gen.MoveNext()); // False
// ── What is still NOT possible (verified engine behavior) ── // ✗ 1. A namespace name that collides with a NON-namespace member is an error var Json = 5; namespace Json { int x = 1; } // ✗ error: collides with existing member 'Json' // ✗ 2. Two bundles exporting the same class under the SAME alias collide import "a.slcbc" as B; // a.slcbc and b.slcbc both export class Point import "b.slcbc" as B; // ✗ error: class 'Point' collides (same alias) different aliases coexist
Rules & limitations. Declaring into an existing namespace (builtin or user) extends it builtins are cloned copy-on-write per interpreter, so namespace Json { ... } adds members without leaking into other interpreters. Inside the declaring file, members are reachable flat AND qualified (My.Include.add(...)). Script-facing builtins (Json, App, mcp, …) are re-exported through imports. Bytecode bundles resolve bare sibling calls via the function's namespace including siblings in ancestor namespaces and flat members at the namespace root so fwd() → helper() exports and runs; bundle classes are alias-qualified, so same-named classes coexist under different aliases (bare-name use is first-wins).

▼ Built-in Functions

print Output values to the console

Accepts multiple arguments joins them with spaces. In Debug builds, prepends the line number.

print(value1, value2, ...);
print("hello"); // Result: hello print("sum =", 42); // Result: sum = 42
Values are displayed by ONE rule, shared with "a" + value and $"{value}": a Type reports the name a script can write (print(typename("ComNode")) → ComNode, never the CLR name), an array reports its literal form ([1, 2]), and every other value keeps its own ToString(). Interpolation uses the same rule, so all three spellings agree.
sleep Pause execution for a duration (ms)

Blocks the current thread for the specified number of milliseconds. Interruptible via Ctrl+C press Ctrl+C in the REPL to abort sleep() and return to the prompt.

sleep(milliseconds);
sleep(1000); // wait 1 second
ReadLineAsync Non-blocking stdin read for coroutines returns ReadLineRequest, use yield

Non-blocking alternative to Console.ReadLine() designed for use inside coroutines. Returns a ReadLineRequest object immediately; the actual stdin read happens on a background thread. The coroutine suspends via yield and resumes when input is available.

Pattern: var req = ReadLineAsync(); yield req; var line = req.Result;

var req = ReadLineAsync(); yield req; var line = req.Result;
// Inside a coroutine int readLoop() { var req = ReadLineAsync(); yield req; var line = req.Result; print(line); return 0; }
Outside a coroutine, falls back to blocking Console.ReadLine(). Inside a coroutine, the background thread reads stdin while the interpreter continues pumping other coroutines.
Task Async task with background thread pool, continuations, and combinators

The Task namespace provides cooperative async primitives for running script functions with continuations, delays, and combinators. All callbacks run on the main thread, and a wait for one of them keeps a window of yours alive (an await delivers the queued messages, which the async / await entry states) via a marshalling queue no background threads, no thread-safety issues.

Methods

Task.Run(fn)Starts the function on a background thread and returns a Task at once (C#'s shape), so the caller keeps going; await the task (or .Wait() it) to see the result. A Task.Run of an async function is the unwrapping overload: the task it returns completes with the body's own task.
Task.Delay(ms)A pause that holds no thread. Returns a Task that completes when the duration has elapsed, so await Task.Delay(ms) suspends the body and nothing waits on a clock; Task.Delay(ms, token) faults the task instead of completing it when the token fires.
Task.Yield()C#'s yield point: a Task that is incomplete when it is read and completes on a later pass of the run queue, so await Task.Yield() hands control back before the body continues and everything already queued for the run thread is served first. Its value is null.
Task.WhenAll(list)Returns the composite Task at once, complete or not: await it (or call .Wait()) to wait for every task in the list, which is C#'s shape. Accepts array or list literals.

Task instance members

.Wait()Block the calling thread until the task completes.
.ResultGet the return value (blocks if not yet completed).
.StatusReturns "Running", "Completed", or "Faulted".
.ContinueWith(fn)Schedule a callback on the main thread when the task completes. The callback receives the antecedent Task. Returns a new Task for chaining.

Example

var t = Task.Run(fun() { return 40 + 2; }); print(t.Result); // 42 auto-pump ran the callback // Chain: Run → ContinueWith → ContinueWith Task.Run(fun() { return 10; }) .ContinueWith(fun(t) { return t.Result * 2; }) .ContinueWith(fun(t) { print("Chain: " + t.Result); }); // 20 // Delay blocks synchronously no .Wait() needed Task.Delay(500); // Cancellation dispose when done var cts = new CancellationTokenSource(); Task.Run(fun() { }, cts.Token); cts.Cancel(); cts.Dispose(); // WhenAll + ContinueWith fires before next statement var done = false; var a = Task.Run(fun() { Task.Delay(30); return 1; }); var b = Task.Run(fun() { Task.Delay(50); return 1; }); await Task.WhenAll([a, b]); // waits for both, and the wait keeps the window alive print(done); // true were they both set above?
All callbacks run on the main thread no background threads, no thread-safety issues. Nothing to pump by hand needed: the marshalling queue is drained automatically after every top-level statement.

Concurrency Quick Reference

PatternBest toolWorks in parallel callbacks?Example
Single collection add/setInternal _syncRoot (automatic)✅ Yeslist.Add(x); dict[k] = v;
Atomic increment/addInterlocked.*❌ No (ref scope-bound)Interlocked.Increment(ref x)
Compound (read-modify-write)Monitor.Enter/Exit or lock {}✅ YesMonitor.Enter(lk); sum=sum+x; Monitor.Exit(lk);
Parallel loopParallel.Range/Each✅ Yes (uses Monitor internally)Parallel.Range(0, 100, (i) => { ... })
CancellationCancellationTokenSource✅ Yesvar cts = new CancellationTokenSource(); cts.Cancel(); cts.Dispose();
Parallel Parallel loop and invocation helpers

The Parallel namespace distributes work across the thread pool. All methods block until the work completes.

Methods

Parallel.Range(start, end, body)Iterate from start to end (exclusive) on the thread pool. Each iteration calls body(i). For ranges <256, one task per item; larger ranges are partitioned into chunks.
Parallel.Range(start, end, step, body)Same with custom step.
Parallel.Each(list, body)Iterate over each element of the list/array on the thread pool. Calls body(element).
Parallel.Invoke(fn1, fn2, ...)Run all functions in parallel. Blocks until all complete.

Example

var sum = 0; var lk = new object(); Parallel.Range(0, 100, fun(i) { Monitor.Enter(lk); sum = sum + i; Monitor.Exit(lk); }); print(sum); // 4950 Parallel.Invoke( fun() { print("task 1"); }, fun() { print("task 2"); } );
Thread safety: Parallel callbacks run on the thread pool. Use Monitor.Enter/Exit for compound operations. Simple collection operations (list.Add, dict[key]=value) are internally locked.
Interlocked Atomic operations on variables

The Interlocked namespace provides atomic read-modify-write operations. These work on the main thread and should not be used inside Task.Run or Parallel callbacks (the ref mechanism is scope-bound and cannot cross threads).

Methods

Interlocked.Increment(ref int)Atomically increments a variable. Returns the new value.
Interlocked.Decrement(ref int)Atomically decrements a variable. Returns the new value.
Interlocked.Add(ref int, int)Atomically adds a value. Returns the new value.
Interlocked.Exchange(ref int, int)Atomically sets a variable and returns the old value.
Interlocked.CompareExchange(ref int, int, int)Atomically sets a variable if it matches the comparand. Returns the old value.
Monitor Thread synchronization primitives

The Monitor namespace provides mutual-exclusion locking. Works in both main-thread and thread-pool callbacks. Use a dedicated object as the lock do not lock on collections or strings.

Methods

Monitor.Enter(object)Acquires an exclusive lock on the object. Blocks if another thread holds the lock.
Monitor.Exit(object)Releases the lock. Always pair with Enter in a try/finally block.
Monitor.TryEnter(object)Tries to acquire the lock without blocking. Returns true if successful.
Monitor.TryEnter(object, ms)Tries to acquire the lock with a timeout. Returns true if acquired within the timeout.

Example

var counter = 0; var lk = new object(); var tasks = new List<Task>(50); var i = 0; while (i < 50) { var ci = i; tasks.Add(Task.Run(fun() { Monitor.Enter(lk); counter = counter + 1; Monitor.Exit(lk); })); i = i + 1; } await Task.WhenAll(tasks); print(counter); // 50
Always use try/finally to ensure Exit is called even if the protected code throws:
Monitor.Enter(lk); try { ... } finally { Monitor.Exit(lk); }
beep Play a beep sound

Plays a beep at the given frequency (Hz) and duration (ms).

beep(frequency, duration);
abort Immediately terminate script with exit code

Immediately terminates script execution and sets the process exit code. The exit code becomes visible to the OS or calling process abort(0) means success, any non-zero value indicates an error. Equivalent to exitcode = N; throw ScriptAbortException;.

abort(exitCode);
abort(42); // exits with code 42 abort(0); // exits with code 0 (success)
atexit Register a cleanup function to be called when the script exits (like C's atexit)

Registers a function that will be called when the script terminates either via exit() / abort() or by reaching the end of the script normally. Handlers are invoked in reverse order of registration (LIFO, like C's atexit). If a handler throws an exception, the remaining handlers still execute. Accepts a single function or an array of functions.

atexit(handlerFunction); atexit([fn1, fn2, fn3]); // register multiple at once
var cleanup = fun () { print("cleaning up..."); }; atexit(cleanup); // Multiple handlers invoke in LIFO order var closeDB = fun () { print("closing DB"); }; var saveFile = fun () { print("saving file"); }; atexit([closeDB, saveFile]); exit(0); // Output: // saving file // closing DB // cleaning up...
Handlers are invoked even if the script exits via exit(N) or abort(N), and also on normal completion. Each handler must be a lambda (a Function) with no parameters. The handler list is cleared after invocation handlers run only once.
exit Alias for abort terminate script with exit code

Same as abort(N). Sets the process exit code and immediately terminates script execution.

The codes the engine ITSELF uses have names, so a script says what it means instead of writing a digit: ExitCode.Ok (0), ExitCode.Failed (1), ExitCode.Usage (2) and ExitCode.Refused (3). They are the values the command line already answers with, so naming them changed no number: both --compile and --dump-bytecode use Usage when a file, an output path or a flag could not be used, and Refused when the work was declined with a reason on stderr. The code a run is ENDING with is readable as exitcode (or Environment.ExitCode), which a catch sees after an exit() it caught: an exit(9) that was caught leaves both at 9, so a script that needs a different verdict must set it itself.

exit(exitCode); exit(ExitCode.Refused);
exit(42); // same as abort(42) exit(ExitCode.Usage); // 2: the caller got a file, a path or a flag wrong
exit(N) is an alias internally it calls the same ScriptAbortException mechanism as abort(N).
exitcode is the SCRIPT's verdict, and only a script decides one. Reading it answers the code the run is ending with, and exit(N) is what sets it. A failure the ENGINE reports does not: a file whose script stops on an error, and a bundle the engine cannot LOAD at all, both leave exitcode alone and let the session go on, because neither ran a script that could decide anything. So in a REPL, .run a.slc over a script that fails prints its one Error: line and leaves exitcode at 0, while a script that reaches exit(CheckFailed()) sets it to 1. The file's own verdict line says which happened (Done: 1 file(s) ... (1 failed to load or run)), and the CLI agrees in the other direction: the same unreadable bundle given as the command's argument exits 1, because there the file IS the whole run.
typeof Get the friendly type name of a value

Returns a string representation of the runtime type (e.g., "int", "string", "List<int>").

A NAMED VARIABLE ANSWERS ITS DECLARATION, whatever it holds. A value has a runtime type and reports it (the erasure rule above), but a variable IS the type it was declared with, across every assignment: long? db; is "long?" before and after db = Sqlite.OpenDb(...), where reporting the value’s type made one variable answer two names in a single run. So typeof(x) reads the declaration when it can name one, and falls back to the value’s type when there is no declaration to read. The declaration is read for a top-level variable and for a local, from a file and from a compiled entry alike, so a --source=strip bundle answers the same name for the same declaration. Three shapes still report the value’s type, consistently on both engines: an object-typed declaration (the same shape as var to the compiler, so neither records a type), a PARAMETER (no declared type on its binding), and a class FIELD or a captured local read from inside a compiled body. A non-name operand (typeof(42), typeof(this.Field), typeof(null)) always reports the value.
typeof(value);
print(typeof(42)); // "long" print(typeof("hi")); // "string" print(typeof((1, 2))); // "Tuple" (registry name, not the CLR "Tuple")

For internal script-exposed types, typeof returns the script-facing name from the type registry: a functional name with no namespace and no CLR prefix ("Tuple", "KeyValuePair", "ErrorInfo"). Those are the same names print() uses, so the two stay aligned, and each is a name a script can write back.

A class or struct instance reports its declared name typeof(new Animal("Rex")) is "Animal", not "Class". The runtime storage type is the same ClassInstance for every class, so naming it after the storage class would report a category that resolves to nothing it is unusable with is/as, a cast, or Json.Deserialize(type, json). is Class / is Struct are unaffected: they match the contract keyword, exactly as l is List stays true for a list whose typeof is "List<int>".

A type NAME used as a value reports the same way. typeof(Animal) is "Animal" and typeof(Pt) is "Pt", the declared name rather than "ClassInfo" (the storage class of the engine's type object, again a category). A generic type reference reports its whole spelling, so typeof(Dictionary<string, object>) is "Dictionary<string, object>"; that is also the only way to name a parameterized type the runtime value cannot report. A value's own name keeps what the declaration said where it can: a container built from a NULLABLE element keeps the mark (typeof(new List<string?>(...)) is "List<string?>"), while a nullable variable reports the runtime type the annotation erases into (int? n = 1; gives typeof(n) = "int"), which is what C# does at runtime. is ClassInfo stays the contract over every one of them.

For the list of internal type names supported by typeof that can be used with is / as, see the is entry.

typename Get the System.Type object for a type name string

Accepts a string type name ("int", "double", "string", "bool", etc.) and returns the corresponding .NET Type object.

The SAME lookup is uses resolves the name, so anything the language accepts as a type resolves here too: the built-in keywords above, every name in the script-facing type registry ("ComNode", "ErrorInfo", a UI type, …), and a CLR type name such as "DateTime" or "StringBuilder". Two things do not: a name the language does not know (reported as Unknown type name: …), and a script-declared class or struct, which has no .NET type to hand out even though is/as accept it by name.

typename("typeName");
var t = typename("int"); print(typeof(t)); // "Type"
nameof The source name of an expression, as C# writes it

Returns the last identifier as written and evaluates nothing: the same rule and the same answers as C# nameof. A name gives its own identifier, a member gives its member name, and a type gives its simple name with no type arguments.

nameof(expression);
var items = new List<string>(...); print(nameof(items)); // "items" the variable's own name print(nameof(items.Count)); // "Count" the member's name, not its value print(nameof(TaskStatus.Running)); // "Running" print(nameof(List<int>)); // "List" (no type arguments, like C#) print(nameof(List<string?>)); // "List" (a nullable argument is allowed and ignored) // Compare with a stored string if (dbValue == nameof(CronType.Queue)) print("Queue task");

Every position C# allows works the same way: a local, a parameter and a capture inside a lambda, a member reached through a type (nameof(Tn1.V) is "V"), and a member reached through a namespace (nameof(Json.Serialize) is "Serialize"). The spelling is kept as written, so nameof(Name) is "Name".

Nothing is evaluated, so there is no side effect and no value to fail on: the name is the expression's TEXT, resolved where the call is parsed. That is also why a keyword type on its own has nothing to name (nameof(int)) and a top-level ? is not a name (nameof(int?)), the two refusals C# makes as well.
An enum member is the case this replaces most often: the value stored as text in a database is compared against nameof(CronType.Queue) directly.
AssertEqual Test equality with formatted output

Compares expected vs actual values. Prints PASS/FAIL with the provided message.

AssertEqual(expected, actual, "message");
AssertEqual(30, 10 + 20, "10 + 20 = 30"); // Result: ✅ 10 + 20 = 30
AssertTrue Test a condition with formatted output

Checks if a condition is true. Prints PASS/FAIL with the provided messages.

AssertTrue(condition, "pass message", "fail message");
AssertTrue(3 * 6 == 18, "3 * 6 = 18", "3 * 6 <> 18"); // Result: ✅ 3 * 6 = 18 AssertTrue(false, "won't show", "something broke"); // Result: ❌ something broke
Check Assert a condition native battery Check (pass/fail counter)

The native transpose of the battery pattern's void Check(string name, bool ok) {...} opener: increments the native pass/fail counters and prints ✅ label on pass / ❌ label on failure (exact battery format). Returns ok.

A script-defined void Check(...) shadows the native (the engine is re-declarable) existing batteries that define their own local Check keep working unchanged.
Thread-safe counters: the pass/fail counters are incremented with Interlocked.Increment and read with Volatile.Read, so Check is safe to call from Parallel.Range / Parallel.Each / Parallel.Invoke worker threads on the same interpreter no lost updates (stdout lines may interleave, which is cosmetic). Note: imports run on the same thread and bytecode-loaded libraries have their own interpreter instance (own counters), so neither needs synchronization.
Check("label", condition);
Check("a", 1 == 1); // Result: ✅ a Check("b", 1 == 2); // Result: ❌ b
A failed check is REMEMBERED, not only printed: the native keeps the label of every failing check with the position it was reported at (up to 32, then a count), so a run can say WHY it ended. A suite's tail is CheckSummary(); exit(CheckFailed());, where the code is the SCRIPT's own decision and the verdict alone would read 1 and nothing else: an embedding host now reads Checks (its counts and the failing labels) and, through slc_file in SQLite, the same report as ReturnValue, with the value the run ended with inside it named for where it came from: Answer for a top-level return <value>, Echo for the value of the last expression statement (the = ... a REPL prints), so the false of CheckSummary() can never be read as a verdict. The counters live on the RUNNING interpreter, so a hosted session reports its own run rather than the interpreter that registered the native.
CheckSummary Print the native battery closing block

Prints a blank line, then ═══ N passed, M failed ═══, then ✅ ALL TESTS PASSED (or ❌ M TEST(S) FAILED when failures occurred). Returns true iff failed == 0.

CheckSummary();
CheckSummary(); // Result: (blank) // Result: ═══ 1 passed, 1 failed ═══ // Result: ❌ 1 TEST(S) FAILED CheckReset(); CheckSummary(); // Result: (blank) // Result: ═══ 0 passed, 0 failed ═══ // Result: ✅ ALL TESTS PASSED
CheckPassed Native Check family passed-checks counter

Returns how many checks passed since the last CheckReset.

CheckPassed();
CheckPassed() // Result: 1
CheckFailed Native Check family failed-checks counter

Returns how many checks failed since the last CheckReset.

CheckFailed();
CheckFailed() // Result: 1
CheckReset Zero the native Check counters

Zeroes the native Check/CheckSummary counters the native transpose of the battery's int passed = 0; int failed = 0; opener. Explicit, not automatic: counters persist across REPL lines until reset.

CheckReset();
CheckReset(); Check("a", 1 == 1); Check("b", 1 == 2); print("failed=" + CheckFailed() + " passed=" + CheckPassed()); var ok = CheckSummary(); print("summary returned " + ok); // Result: // ✅ a // ❌ b // failed=1 passed=1 // (blank) // ═══ 1 passed, 1 failed ═══ // ❌ 1 TEST(S) FAILED // summary returned False
LoadAssembly Load a .NET assembly from a file (not AOT compatible)

Reads the assembly bytes from disk and loads it. Returns the Assembly object. Use with GetType and CreateInstance.

LoadAssembly("path/to/lib.dll");
Not available in an AOT-compiled build, which is the shipped one: the call throws a catchable refusal that says why. A script that must work on both asks RuntimeFeature.IsDynamicCodeSupported first, which is False in that build and True under the JIT one. Loading types in a HOST process does not help either: a host cannot hand its own loaded types to a script.
Invoke Universal call lambda or named function, delegate, function pointer, .NET method

Multi-purpose invocation that handles four distinct callable types:

  • Function named functions and lambdas
  • a delegate lambdas cast to a delegate type via as
  • Function pointer native function pointers obtained from a library object
  • MethodInfo .NET reflection methods from GetType / LoadAssembly
Invoke(callable, args...); Invoke(obj, "methodName", args...);
// 1. Invoke a plain lambda int add(int a, int b) { return a + b; } var r1 = Invoke(add, 10, 20); print(r1); // Result: 30 // 2. Invoke a lambda cast to a delegate type var act = fun(int x) { print("got: " + x); } as Action`1; Invoke(act, 42); // Result: got: 42 // 3. Invoke a native function pointer (Sleep) var kernel = LoadLibrary("kernel32"); var sleepPtr = kernel.GetFunctionPointer("Sleep"); Invoke(sleepPtr, 1000); // sleep 1s FreeLibrary(kernel); // 4. Simpler: DynamicLibrary auto-resolves function pointers var k = LoadLibrary("kernel32"); // the library object answers its exports k.Beep(800, 300); // auto-resolves Beep k.Sleep(1000); // auto-resolves Sleep k.Free(); // releases handle
Arity here: the required arguments are enforced, extras are ignored. A callable reached through Invoke must receive at least the arguments its declaration REQUIRES a params tail is zero-or-more and a defaulted parameter is optional. Too few is REFUSED with the count (Expected at least 2 arguments, got 1) rather than binding the gap as null, and a params function receives exactly the arguments you passed (Invoke(CountArgs, "a") sees ONE). Extra arguments are ignored, never refused, which is what keeps Com.Run(() => { … }) a callback that ignores the scope it is handed legal.
This is the NAKED call: nothing is injected and no lifetime is held. When a script wants the SCOPED shape a subject created, handed to a body, released when the body returns that is an ordinary helper in the language rather than a namespace: Com.Run and Task.Run are the two namespaces that own a Run, and the generic form is a using-based helper (the Com entry shows it).
RunScript Execute a script string or file in a sub-interpreter

Creates a new interpreter instance to run the provided source code. Optionally treat the source as a file path. With preserveContext, executes in the current scope so variables, functions, and classes persist across calls.

RunScript(source, isFilePath, preserveContext, cancellationToken);

Parameters:

ParamTypeDescription
sourcestringScript source code or file path
isFilePathboolIf true, source is a file path; the file is read and executed
preserveContextbool?If true (default false), runs in the current interpreter scope instead of a fresh sub-interpreter. Variables, functions, and classes persist across calls, enabling state-machine patterns
cancellationTokenCancellationToken?A KILL SIGNAL for THIS run: the engine asks it between statements, at a loop back-edge and inside sleep, so a cts.Cancel() from another thread stops the run where it is and the result carries Stopped: the run was cancelled. Without one, cancelling has nowhere to land

A file path follows the engine's one path rule: ./x.slc is a file beside the running script, so a program that ships with its helpers next to it works from any directory, any other relative spelling is against the process directory, and an absolute path is taken as it is. The refusal names the path it actually resolved, so a miss reads as a path rather than as a mystery. A compiled bundle is not source text: handing a .slcbc to RunScript is refused by name, naming the two doors that do run one (Bytecode.LoadScript(path) and call the entry it answers, or import "x.slcbc" as Alias for a library bundle), instead of failing later in the lexer on the file's bytes.

// beside the running script, whatever the process directory is var r = RunScript("./helper.slc", true); // a bundle needs the door that loads one var entry = Bytecode.LoadScript("./tool.slcbc"); if (entry is Function) { entry(); }
// Isolated mode (default) var r = RunScript(@"return 42;", false); print(r.ReturnValue); // 42 // preserveContext=true state machine across calls RunScript(@"var counter = 0;", false, true); RunScript(@"counter = counter + 1; return counter;", false, true); // counter is now 1 persists because preserveContext=true

The return value is a Result value with .HasError, .ErrorMessage, .ReturnValue, .ExitCode, and .StackTrace properties. It can be serialized with Json.Serialize(result).

A diagnostic raised inside the nested script is reported at the CALL. The source is usually a string literal in this file, so a position inside that text would send you to a line that is not there: a warning about a nested one-liner reads [L36:C5], the line of the RunScript(...) call, rather than line 1 of the nested text. A nested file keeps its own positions, since you can open it, and a refusal keeps its own detail in the message either way: ErrorMessage still carries (at line N, column N) of the nested statement.

The nested run is compiled the way a command-line run is (parse, precompile, interpret), so a function it declares has bytecode and its body runs on the VM in both modes. That is what makes the same text behave the same whoever runs it: a shape only the VM can finish, such as two awaits in one expression, works here rather than being refused by the tree walker. Pinned by runscript_context_test section 6.

NativeAOT note: the engine keeps a single instance of the natives it also binds itself (today: sqlite3): loading that name by path resolves to the copy beside the executable, so a path load is safe and both forms address the same library. Other natives load from the path you give, as usual, and are never duplicated silently.

LoadLibrary Load a native DLL and return a DynamicLibrary handle

Returns a DynamicLibrary object that automatically resolves function pointers when you call methods on it. Numeric, pointer and string arguments are supported: a string is marshaled as a NUL-terminated UTF-8 block and freed after the call. That is one convention for every native call a script makes lib.name(…), lib._42(…), lib.Invoke(name, …) and CallNative all share it so call the ANSI entry points (…A): a …W entry point would read those bytes as UTF-16. If you must call one, the Win32 namespace's ToPointer("text") builds the UTF-16 pointer for you. The namespace's CallFunc goes through this same step, so it sends the same bytes as CallNative.

A handle also reports what it has resolved so far useful to see what a script has actually called into:

MemberReturnsNotes
lib.NamestringThe name it was loaded with.
lib.HandleIntPtrThe native module handle (a number in JSON).
lib.Functionsstring[]The export names resolved so far, in resolution order. A snapshot read it again after resolving more. This is what the handle has resolved, not the DLL's export table: listing every export means walking the PE export directory, which is not bound here.
lib.Ordinalsint[]The ordinals resolved so far, same snapshot semantics.

Invoking an export whose name is only known at runtime walking lib.Functions, say is what lib.Function(name|ordinal) is for: it returns a callable handle. For a name written literally, lib.someName(...) is shorter and does the same thing.

lib.Invoke(name|ordinal, args…) is the one-call shorthand for lib.Function(name).Invoke(args…), with lib.InvokeRaw / lib.InvokeStr / lib.InvokeDouble beside it same marshaling, same guess, one line fewer.

A pointer carries no signature, so .Invoke() guesses narrowly, and safely. A return value that points into committed, readable memory (checked with VirtualQuery) is read as a NUL-terminated C string; anything else comes back as an integer. A small integer is therefore never dereferenced, and a wrong guess cannot kill the process (Invoke() on sqlite3_libversion gives "3.51.3", on sqlite3_libversion_number gives a number). When you know the signature, say so instead of relying on the guess: .InvokeRaw() (the machine value), .InvokeStr() (read the result as a C string it throws rather than reading unreadable memory), .InvokeDouble() (unavoidably explicit: a double return is bit-identical to an int64 one, so it cannot be guessed at all). Argument strings are marshaled as UTF-8 and freed after the call, matching CallNative. Width caveat: an int-returning export comes back as the 64-bit machine value, so a negative result is not sign-extended lib.Invoke("sqlite3_stricmp", "abc", "abd") yields 4294967295, which is -1 as a 32-bit int. Compare with != 0, or narrow it yourself (x > 2147483647 ? x - 4294967296 : x). The handle exposes .Name, .Ordinal (-1 when resolved by name) and .Pointer.
// What has this handle actually called into? var lib = LoadLibrary("sqlite3"); var p = lib.GetFunctionPointer("sqlite3_libversion"); foreach (var f in lib.Functions) print(f); // sqlite3_libversion print(Json.Serialize(lib)); // {"Name":"sqlite3","Handle":…,"Functions":[…],"Ordinals":[]} // Invoke one by name, then by ordinal both give the same handle shape print(lib.Function("sqlite3_libversion").Invoke()); // "3.51.3" guessed as a C string print(lib.Function("sqlite3_libversion_number").Invoke()); // 3051003 guessed as a number var byOrd = lib.Function(1); // .Ordinal == 1, .Pointer is the address lib.Free();
var lib = LoadLibrary("kernel32"); var lib2 = LoadLibrary("user32"); // a second library, tracked the same way
// Numeric args: Beep(freq, dur), GetTickCount() var k = LoadLibrary("kernel32"); k.Beep(800, 200); print("Uptime: " + k.GetTickCount()); k.Free(); // String args: MessageBoxTimeoutA(HWND, text, caption, type, langId, timeoutMs) the ANSI // form, because script strings are marshaled as UTF-8; a …W entry point reads them as UTF-16 var u = LoadLibrary("user32"); var r = u.MessageBoxTimeoutA(0, "Hello", "Test", 0, 0, 3000); print("result: " + r); // Result: 0 (timeout) or 1 (OK) u.Free(); // Ordinal calls: _NNN syntax resolve by ordinal instead of name var k2 = LoadLibrary("kernel32"); k2._117(700, 150); // Beep at ordinal 117 var p = k2.GetFunctionPointer(117); // cached pointer lookup print("Beep ptr: " + ToHex(p)); var p2 = k2.Function(117).Pointer; k2.Free();
The DynamicLibrary is also available via LoadLibrary(). The function pointer cache is per-object subsequent calls to the same method reuse the cached pointer. All loaded libraries are freed automatically on .reset all. Ordinal calls (_NNN) are faster than by name and useful for undocumented APIs. Use dumpbin /exports your.dll to find ordinals for your build.
FreeLibrary Unload a native DLL

Frees a previously loaded native library. Accepts a DynamicLibrary object or a raw IntPtr (for backward compatibility with the old LoadLibrary API).

FreeLibrary(lib); // DynamicLibrary object FreeLibrary(handle); // raw IntPtr (numeric) lib.Free(); // method on DynamicLibrary
var k = LoadLibrary("kernel32"); k.Beep(600, 100); FreeLibrary(k); // same as k.Free() print("freed"); // Result: freed
ClearPureCache Clear the pure function memoization cache

Clears all cached results from pure functions. Useful when external state changes invalidate cached values, or to measure pure function performance without cache interference.

ClearPureCache();
ClearPureCache(); var size = GetPureCacheSize(); // 0
GetPureCacheSize Get number of entries in the pure function cache

Returns the current number of cached results in the pure memoization cache. Useful for debugging and performance analysis.

var n = GetPureCacheSize();
pure int sq(int x) { return x * x; } sq(1); sq(2); sq(3); print(GetPureCacheSize()); // 3
GetScriptDepth Get current interpreter nesting depth

Returns the current interpreter stack depth. Increases by 1 for each RunScript call, decreases on return.

var d = GetScriptDepth();
var r = RunScript("return GetScriptDepth();"); print(r.ReturnValue); // 2 (nested)
TypeName Get .NET full type name (different from typename)

Returns the full .NET type name, e.g. "System.Int32". Different from typename(), which turns a type-name string into the .NET Type object itself.

var name = TypeName(value);
print(typename("int")); // System.Int32 the Type object print(TypeName(42)); // "System.Int32"
CreateTimer Periodic timer CreateTimer(intervalMs, callback), with .Start() / .Stop()

Creates a periodic timer that invokes a callback at the given interval (milliseconds). The returned TheTimer lets you change the interval, swap the callback, and stop/restart it. Ticks fire on the UI/main thread the callback is dispatched through the window message pump (like a button Click), so it is safe to touch forms, controls and COM objects from inside it; it runs only while the app is pumping (inside Application.Run / Application.DoEvents).

var t = CreateTimer(intervalMs, callback); // created started var t = CreateTimer(); // manual: set .Interval/.Tick, then .Start()

Members (on the returned timer):

  • .Interval (int, ms) change the period (restarts when running).
  • .Tick callback (sender, e) => { ... }; invoked on the UI thread every interval.
  • .Start() / .Stop() start or stop the timer; call Stop() before closing a form so the tick cannot touch disposed controls.
  • .Enabled (bool) set at creation to start/stop immediately.

A tick that raises a script error is reported, and the timer keeps its schedule. A tick body runs inside a window procedure, so a failure there cannot unwind into your script: the engine writes it to the log once, with the position ([ERROR] [L4:C27] Timer: Undefined variable 'total'), and the next tick runs as usual. The SAME failure is not repeated, because a timer fires on its interval and an unchanged message would print one line per tick; a tick that succeeds forgets it, so a later, different failure is reported too.

// live-refresh timer, stopped on form close (see ui/demos/wmp_player.slc) var infoTimer = CreateTimer(500, (object s, EventArgs e) => { infoLabel.Text = wmp.currentMedia.name + " " + wmp.controls.currentPosition; }); // manual form count, then stop after 10 ticks var count = 0; var timer = CreateTimer(); timer.Interval = 1000; timer.Tick = fun(sender, e) { count = count + 1; print("tick " + count); if (count >= 10) timer.Stop(); // no more ticks }; timer.Start();
Timers must be created and stopped on the main thread. If your app has no message pump running, ticks are deferred until the next DoEvents/Run cycle. Always Stop() in the form's Closing handler or right after Application.Run returns.
CallNative Call a C function pointer (CDECL), returns long

Calls a native C function by pointer using the CDECL calling convention (compatible with SQLite, libcurl, and most C libraries). String arguments are automatically converted to UTF-8 pointers and freed after the call. Numeric/pointer args pass through as long.

Use with LoadLibrary() to resolve function pointers.

var rc = CallNative(fnPtr, arg1, arg2, ...);
// sqlite3_exec(db, sql, callback, userData, errmsg) var execPtr = sqlite.GetFunctionPointer("sqlite3_exec"); var errBuf = Mem.Alloc(8); var rc = CallNative(execPtr, dbPtr, "CREATE TABLE t(x)", 0, 0, errBuf);
String arguments are converted to UTF-8 via Marshal.StringToCoTaskMemUTF8 the engine's one convention for native calls, shared with the namespace's CallFunc and the DynamicLibrary surface. For UTF-16 (Windows API) strings, the Win32 namespace's ToPointer(str) builds the pointer. Null pointer throws ArgumentException instead of crashing.
CallNativeDbl Call a C function returning double (CDECL)

Same as CallNative but reads the return value from the XMM0 register (floating-point). Use for C functions returning double (e.g. sqlite3_column_double).

var val = CallNativeDbl(fnPtr, arg1, arg2, ...);
// sqlite3_column_double(stmt, i) var avg = CallNativeDbl(dblPtr, stmt, 0);
CallNativeStr Call a C function returning const char* → UTF-8 string

Same as CallNative but reads the returned pointer as a UTF-8 (ANSI) string via Marshal.PtrToStringAnsi. Use for C functions returning const char* like sqlite3_column_name, sqlite3_column_text, or sqlite3_errmsg.

var s = CallNativeStr(fnPtr, arg1, ...);
// sqlite3_column_name(stmt, i) → UTF-8 string var colName = CallNativeStr(namePtr, stmt, 0);

▼ TCP Networking

Server TCP server accept clients, send/receive messages, optional HTTP static file serving

Create a TCP server with Server.Create(port, mode, name, rootDir?). Set callbacks before calling Server.Start(). Then call host.Listen() to start the dispatch loop.

When rootDir is provided, the server also serves static files over HTTP on the same port like a mini python -m http.server. Set mode to "external" to bind to all interfaces (0.0.0.0).

var host = Server.Create(8080, "external", "FileServer", "C:/www"); Server.Start(); host.Listen();

After starting, files in C:/www are available at http://localhost:8080/index.html. The connection probe reads the request head and lets the Sec-WebSocket-Key header decide, so the folder and a WebSocket session share one port: an upgrade goes to the handshake, and anything else opening with GET / is served from the folder. The head is handed to the handshake rather than read twice, so a client that sends its first frame in the same packet is not truncated. docs/networking/howto.html is the worked guide, with the modes, the file statuses and the members it does not have room for here.

HTTP Response Codes

CodeWhen
200 OKFile found and served
403 ForbiddenPath traversal detected (../ outside root)
404 Not FoundFile does not exist
405 Method Not AllowedNon-GET request

Content-Type Mapping

ExtensionContent-Type
.html .htmtext/html; charset=utf-8
.csstext/css; charset=utf-8
.jsapplication/javascript
.jsonapplication/json
.pngimage/png
.jpg .jpegimage/jpeg
.gifimage/gif
.svgimage/svg+xml
.icoimage/x-icon
.pdfapplication/pdf
.zipapplication/zip
.txt .mdtext/plain; charset=utf-8
.wasmapplication/wasm
otherapplication/octet-stream
// WebSocket server with HTTP file serving var host = Server.Create(8888, "external", "FileServer", "C:/www"); host.OnMessage(fun(c, m) { print("WS: " + m); }); Server.Start(); print("HTTP: http://localhost:8888/index.html"); host.Listen();
Client TCP client connect to a server

Create a client with Client.Create(host, port [, timeoutMs]), where the third argument is the connect timeout in milliseconds (15000 by default) and not a mode. It is IDEMPOTENT per interpreter, like Server.Create: a second call answers the first client and its host and port stay those of the first call, so a script holds one client and reconnects with Disconnect() then Connect(). Set callbacks to handle connection and messages. Connect() answers whether the WebSocket handshake completed, so a refused port, a timeout or a server that does not upgrade all return false and report through OnError; client.IsConnected is the property to poll afterwards, and OnId firing is the moment the session is usable. docs/networking/howto.html is the worked guide.

var client = Client.Create("localhost", 8080, "internal"); client.OnMessage(fun(msg) { print("got: " + msg); });
ClientStatus TCP client status enum

Values returned by the clients dictionary from host.Clients().

ClientStatus.Pending waiting for ACK ClientStatus.Connected fully registered ClientStatus.Disconnected disconnected
Listen Server: block and dispatch events until server stops

Call host.Listen() after host.Start() to process client connections and messages. Blocks until the server stops. Use host.Pump() for a non-blocking dispatch loop.

host.Listen();
var host = Server.Create(8080); host.Start(); host.OnMessage(fun(id, m) { print(m); }); host.Listen(); // blocks
Wait Client: block and dispatch events until disconnected

Call cli.Wait() after connecting to process incoming messages. Blocks until the client disconnects. Use cli.Pump() for a non-blocking alternative.

cli.Wait();
var cli = Client.Create("localhost", 8080); cli.OnMessage(fun(m) { print(m); }); cli.Connect(); cli.Wait(); // blocks until disconnect
Pump Non-blocking dispatch for Server and Client

Available on both Server and Client. Drains the dispatch queue immediately without blocking. Use in a coroutine loop to interleave event processing with other work instead of Listen()/Wait().

host.Pump(); cli.Pump();
while (true) { cli.Pump(); yield; }
See ws_chat_client.slc for a full interactive example.
Stop Gracefully stop a running server

Call Server.Stop(hostName) to stop a server by name. All active connections are closed. The Listen() loop then exits.

Server.Stop("MyServer");
// From a coroutine or event handler, stop the server Server.Stop("MyServer"); print("Server stopped");

▼ System Classes

Console Standard input/output/error stream access

Static class for console I/O. print() uses Console.WriteLine internally. Note that standard input/output in script mode goes through the interpreter's captured streams.

Console.WriteLine("text"); var input = Console.ReadLine(); Console.ForegroundColor = ConsoleColor.Red;
Console.Beep(); // system beep Console.Clear(); // clear screen Console.WindowWidth; // window columns

Where a print goes: a script class that extends TextWriter

Console.SetOut(writer) and Console.SetIn(reader) take a real TextWriter or TextReader, and a SCRIPT CLASS may be one: declare class Sink extends TextWriter and every write reaches the member of that name on your object (Write(string), WriteLine(string), WriteLine(), Flush(), Dispose()), and class Source extends TextReader answers Read(), Peek() and ReadLine(). A member you do NOT declare behaves as the CLR base does, so no member has to exist: an undeclared WriteLine(string) still reaches your Write(string), and an undeclared Flush does nothing. The class keeps its own identity (typeof still names it) and gains a CLR FACE it is handed over as, cached per instance; TextWriter and TextReader are the two bases this engine bridges, and any other base is refused by name.

class Sink extends TextWriter { public List<object> lines; public Sink() { lines = [].ToList(); } public void WriteLine(string s) { lines.Add(s); } } var sink = new Sink(); var saved = Console.Out; Console.SetOut(sink); // a script object where a TextWriter is expected print("captured"); // reaches Sink.WriteLine Console.SetOut(saved); print(sink.lines.Count); // 1

The reader is the same mechanism the other way, and it is how a script tests a prompt-driven path: give Console.SetIn a TextReader whose ReadLine returns null at end of input.

A REDIRECT WINS, in an embedded session too: print writes to whatever Console.Out is, so a script that calls Console.SetOut(sink) keeps its own output even when the host installed an output callback (ScriptLangCore.Launcher.exe is such a host). That precedence is what makes a tool that tees its output into a log work identically from the command line and inside a host.

Two limits worth knowing: the CLR wraps whatever SetOut is given in its own synchronized writer, so Console.Out cannot be compared with the object you handed over (compare two conversions of the instance instead), and a script class extends a CLR base only through a bridge, so it cannot override a CLR member's behaviour that the bridge does not forward.

ConsoleColor Console text color enumeration

Used with Console.ForegroundColor and Console.BackgroundColor.

ConsoleColor.Red, ConsoleColor.Green, ConsoleColor.Yellow, ConsoleColor.Blue, ConsoleColor.Cyan, ConsoleColor.Magenta, ConsoleColor.White, ConsoleColor.Gray, ConsoleColor.DarkGray, ConsoleColor.DarkRed, ConsoleColor.DarkGreen, ConsoleColor.DarkYellow, ConsoleColor.DarkBlue, ConsoleColor.DarkCyan, ConsoleColor.DarkMagenta
Math Mathematical functions and constants

Static class with trigonometric, logarithmic, and arithmetic helpers.

Math.PI // 3.14159... Math.E // 2.71828... Math.Sqrt(x) // square root Math.Abs(x) // absolute value Math.Pow(x, y) // x^y
print(Math.Sqrt(16)); // 4 print(Math.Round(3.7)); // 4 print(Math.Floor(3.9)); // 3 print(Math.Ceiling(3.1)); // 4 print(Math.Max(5, 10)); // 10 var r = Math.Sin(Math.PI / 2); // 1

A tie rounds to the EVEN digit, which is C#'s default and therefore Math.Round's: Math.Round(2.5) is 2 and Math.Round(3.5) is 4. A spreadsheet's ROUND rounds a tie AWAY FROM ZERO instead, and the third argument asks for that: Math.Round(value, digits, MidpointRounding.AwayFromZero). The two agree everywhere except on an exact tie, and an exact tie is ordinary in money arithmetic (a product ending in .625 rounded to cents), so a figure copied from a sheet can differ by a cent per tie.

print(Math.Round(2.625, 2)); // 2.62, half to even print(Math.Round(2.625, 2, MidpointRounding.AwayFromZero)); // 2.63, a sheet's ROUND print((2.625).ToString("F2")); // 2.62, the same rule as Math.Round

Formatting follows the same rule as Math.Round, so "F2" and a two-digit round cannot disagree. A decimal takes the same three-argument form and the same default, and it is the type to reach for when the cents have to be exact rather than tolerated.

Environment System environment information

Provides OS version, processor count, tick count, and environment variables.

Environment.OSVersion Environment.ProcessorCount Environment.TickCount Environment.NewLine
print(Environment.OSVersion); // Microsoft Windows NT 10.0.26200.0 var cores = Environment.ProcessorCount; var user = Environment.UserName;
Convert Type conversion utilities (static methods)

Static class for converting between base types.

Convert.ToInt32(val) Convert.ToInt64(val) Convert.ToDouble(val) Convert.ToString(val) Convert.ToBoolean(val) Convert.ToChar(val)
var n = Convert.ToInt32("42"); // 42 var s = Convert.ToString(123); // "123"
Encoding Character encoding and byte conversion

Static properties for common encodings. Useful with Json.SerializeToUtf8Bytes, and with Deserialize when a payload arrives as bytes.

Encoding.UTF8 Encoding.ASCII Encoding.Unicode
var bytes = Encoding.UTF8.GetBytes("hello"); var str = Encoding.UTF8.GetString(bytes); // "hello"
Guid Globally unique identifier

Represents a 128-bit unique identifier. Create new random Guids or parse from strings.

Guid.NewGuid() Guid.Parse(str) g.ToString()
var id = Guid.NewGuid(); print(id.ToString()); // 550e8400-e29b-41d4-a716-446655440000
Random Pseudo-random number generator

Generate random integers or doubles. Create once, call multiple times.

var rng = new Random(); rng.Next(100); // 0-99 rng.Next(10, 20); // 10-19 rng.NextDouble(); // 0.0 - 1.0
var rng = new Random(); var roll = rng.Next(1, 7); // dice roll: 1-6
Regex Regular expression pattern matching (.NET System.Text.RegularExpressions)

Accessible as both a static method class and an instantiable object. All standard .NET regex syntax is supported: anchors (^ $), character classes (\d \w \s), quantifiers (* + ? {n,m}), groups ((expr) (?<name>expr)), alternation (|), and more.

Static Methods

MethodReturnsDescription
Regex.IsMatch(text, pattern[, options])boolReturns true if the pattern matches anywhere in the text
Regex.Match(text, pattern[, options])MatchReturns the first match result (use .Success, .Value, .Index, .Length, .Groups[n])
Regex.Matches(text, pattern[, options])MatchCollectionReturns all matches as a collection (.Count, index access [n])
Regex.Replace(text, pattern, replacement[, options])stringReplaces all occurrences of the pattern with the replacement string
Regex.Split(text, pattern[, options])string[]Splits the text at each pattern match

Instance Methods

Create a Regex object and call methods on it for repeated use with the same pattern. Instance methods do not take a pattern parameter.

var rx = new Regex("pattern"[, RegexOptions]); rx.IsMatch(text) rx.Match(text) rx.Matches(text) rx.Replace(text, replacement) rx.Split(text)
// Static methods var ok = Regex.IsMatch("abc123", "\\d+"); // true var m = Regex.Match("hello 42 world", "\\d+"); print(m.Success); // true print(m.Value); // "42" print(m.Index); // 6 print(m.Groups[0].Value); // "42" (full match) // All matches var all = Regex.Matches("one two three", "\\w+"); print(all.Count); // 3 print(all[0].Value); // "one" // Replace and Split var replaced = Regex.Replace("cat dog cat", "cat", "bird"); print(replaced); // "bird dog bird" var parts = Regex.Split("a,b,c", ","); print(parts.Length); // 3 // Case-insensitive with RegexOptions var ci = Regex.IsMatch("HELLO", "hello", RegexOptions.IgnoreCase); print(ci); // true // Instance reuse pattern var rx = new Regex("a(b+)c"); print(rx.IsMatch("abbc")); // true var m2 = rx.Match("xabbcy"); print(m2.Groups[1].Value); // "bb" print(rx.Replace("xabbcy", "X")); // "xXy"

RegexOptions

Enum passed as the optional options parameter to static methods or the Regex constructor.

ValueNameDescription
1RegexOptions.IgnoreCaseCase-insensitive matching
2RegexOptions.Multiline^ and $ match start/end of each line (not just string)
4RegexOptions.ExplicitCaptureOnly named groups capture
8RegexOptions.CompiledCompile the regex for better performance
16RegexOptions.Singleline. matches newlines
32RegexOptions.IgnorePatternWhitespaceIgnore unescaped whitespace in pattern

Match Result

Returned by Regex.Match(). Properties of interest:

PropertyTypeDescription
.SuccessboolWhether a match was found
.ValuestringThe matched text
.IndexintStarting position of the match in the input
.LengthintLength of the matched text
.GroupsGroupCollectionCaptured groups (.Count, [0] full match, [1] first capture)
AOT note: Match, Group, Capture, MatchCollection, GroupCollection, and CaptureCollection are preserved by [DynamicDependency] for NativeAOT. All common static and instance methods are available. Named group access via Groups["name"] has limited AOT support prefer numeric indexing where possible.
CronExpression Parse and evaluate CRON schedule expressions

Parses standard 5-field CRON expressions and computes the next matching date/time after a given baseline. Fields: minute, hour, day-of-month, month, day-of-week. Supports an optional 6th field (year) and @aliases.

Supported syntax:

TokenMeaningExample
*Any value* * * * * every minute
,Value list1,3,5 * * * * minutes 1, 3, 5
-Range1-5 * * * * minutes 1 through 5
/Step*/15 * * * * every 15 minutes
LLast (day of month/week)0 12 L * * last day of month at noon
WNearest weekday0 0 15W * * nearest weekday to the 15th
#Nth occurrence0 0 * * 5#3 3rd Friday of the month

@aliases: @yearly (0 0 1 1 *), @monthly (0 0 1 * *), @weekly (0 0 * * 0), @daily (0 0 * * *), @hourly (0 * * * *)

Common patterns reference

PatternExpressionDescription
Every minute* * * * *Runs every minute
Every 5 minutes*/5 * * * *Runs every 5 minutes
Every 15 minutes*/15 * * * *Runs every 15 minutes
Every hour0 * * * *At the start of each hour
Every 2 hours0 */2 * * *Every 2 hours
Daily at midnight0 0 * * *Once a day at 00:00
Daily at 2 AM0 2 * * *Once a day at 02:00
Daily at 9 AM0 9 * * *Once a day at 09:00
Twice a day0 0,12 * * *At midnight and noon
Every weekday at 9 AM0 9 * * 1-5Mon–Fri at 09:00
Office hours0 9-17 * * 1-5Every hour 09–17, Mon–Fri
Weekly on Sunday0 0 * * 0Every Sunday at midnight
Weekly on Monday0 0 * * 1Every Monday at midnight
First of month0 0 1 * *First day of each month
Last day of month0 0 L * *Last day of each month
Nearest weekday0 0 15W * *Nearest weekday to the 15th
Nth weekday0 0 * * 5#33rd Friday of the month
Yearly (Jan 1)0 0 1 1 *First day of the year
Yearly with year0 0 1 1 * 2027Jan 1, 2027 only
Year range0 0 1 1 * 2026-2028Jan 1 in 2026, 2027, or 2028
Quarterly (1st day)0 0 1 */3 *Jan, Apr, Jul, Oct
Every 10 minutes (half)0-30/10 * * * *0, 10, 20, 30 past each hour
Weekends only0 0 * * 6,0Saturday and Sunday
var cron = CronExpression.Parse("*/15 8-11 * * *"); var next = cron.GetNextOccurrence(DateTime.Now);

Factory method

MethodReturnsDescription
CronExpression.Parse(expr) CronExpression Parse a 5-field CRON expression string

Instance method

MethodReturnsDescription
.GetNextOccurrence(dateTime) DateTime? Next matching date/time after dateTime, or null if none found within 5 years

Performance

Fields are expanded into HashSet<int> buckets at parse time for O(1) lookup. The next-occurrence scan fast-forwards through non-matching months, days, and hours instead of iterating minute by minute.

// Standard 5-field CRON var cron = CronExpression.Parse("*/15 8-11 * * *"); var t = DateTime.Now; for (var i = 0; i < 5; i = i + 1) { var next = cron.GetNextOccurrence(t); print("Next: " + next); if (next != null) t = next; } // @alias var daily = CronExpression.Parse("@daily"); // 0 0 * * * // Last day of month at noon var lastDay = CronExpression.Parse("0 12 L * *"); // 3rd Friday with year restriction var nth = CronExpression.Parse("0 0 * * 5#3 2027");

Field ranges

FieldPositionRange
Minute10–59
Hour20–23
Day of month31–31
Month41–12
Day of week50–6 (0 = Sunday)
Year (optional)61970–2099
Timezone note: GetNextOccurrence() returns a DateTime? without timezone info (hour-murale). It only compares calendar values (month, day, hour, minute) it does not handle timezone conversion. Use ScheduledTask.NextOccurrence (DateTimeOffset? with local offset) for timezone-aware scheduling.
TimeZoneInfo Represents a timezone used with Scheduler and DateTimeOffset

Wraps .NET System.TimeZoneInfo. Use FindSystemTimeZoneById() to resolve a timezone by Windows identifier (e.g. "UTC", "Romance Standard Time"). Pass null to the scheduler to use server local time.

Factory

MethodReturnsDescription
TimeZoneInfo.FindSystemTimeZoneById(id) TimeZoneInfo Resolve a timezone by its Windows ID (e.g. "UTC", "Romance Standard Time", "Pacific Standard Time")
TimeZoneInfo.Local TimeZoneInfo The server's local timezone
TimeZoneInfo.Utc TimeZoneInfo The UTC timezone

Common timezone IDs (Windows)

IDDisplay
"UTC"Coordinated Universal Time
"Romance Standard Time"UTC+01:00 (Paris, Berlin, Rome)
"Pacific Standard Time"UTC−08:00 (Los Angeles)
"Eastern Standard Time"UTC−05:00 (New York)
"Tokyo Standard Time"UTC+09:00 (Tokyo)
// Use with scheduler var tz = TimeZoneInfo.FindSystemTimeZoneById("UTC"); Scheduler.Add("UtcTask", CronExpression.Parse("0 8 * * *"), (tName) => { print("Fired at " + DateTime.Now); }, tz); // Get local timezone var local = TimeZoneInfo.Local;
Timezone IDs are platform-dependent. On Windows, use standard names like "Romance Standard Time". On Linux/macOS, use IANA names like "Europe/Paris" (requires ICU support).
TaskStatus Status values for scheduled tasks

Enum returned by the .Status property of ScheduledTask. Use the named members instead of string literals for type-safe comparisons.

MemberDescription
TaskStatus.ScheduledTask is waiting for its next occurrence
TaskStatus.RunningTask's callback is currently executing
TaskStatus.StoppedTask was cancelled via Stop() or Remove()
TaskStatus.FailedTask's callback threw an exception (one-shot tasks) or recorded an error via script logic
TaskStatus.CompletedOne-shot task fired, or no more occurrences within 5 years
if (task.Status == TaskStatus.Scheduled) { print("Still waiting"); }
CronType Type of a scheduled task's firing schedule Cron, Queue, or OneShot

Used by ScheduledTask.CronType and stored in the cron_expr column of the task database. Replaces the old string literals "(enqueue)" / "(one-shot)" with a type-safe enum.

MemberValue in DBDescription
CronType.Crona CRON expression (5+ fields)Standard recurring task driven by a CRON schedule
CronType.Queue"Queue"Fire-and-forget: runs on the next Tick(), then self-removes
CronType.OneShot"OneShot"Fires once after a delay or at a specific time, then self-removes
// Check task type (ScheduledTask object) if (task.CronType == CronType.Queue) { print("Enqueued task will fire immediately"); } // From SQLite cron_expr use nameof() var cronStr = row.cron_expr; if (cronStr == nameof(CronType.Queue)) ScheduleEnqueue(name); else if (cronStr == nameof(CronType.OneShot)) ScheduleOneShot(name); else ScheduleCron(name, cronStr, tz);

Two access patterns:

  • task.CronType == CronType.Queue compare the enum directly on a ScheduledTask object
  • cronStr == nameof(CronType.Queue) compare a SQLite cron_expr string via the nameof() built-in

The DB stores the enum name as plain text. Use nameof() to get the string name of any enum value. For recurring CRON tasks, cron_expr holds the raw expression (e.g. "*/2 * * * *") and CronType is CronType.Cron.

ScheduledTask Handle returned by Scheduler.Add/Enqueue/Schedule inspect state, stop or remove

Every Scheduler registration method returns a ScheduledTask handle. Use it to inspect the task state, cancel it, or chain continuations. All tasks are driven synchronously on the calling thread no background threads.

Properties

PropertyTypeDescription
.NamestringUnique identifier (defaults to the CRON expression)
.CronExpressionstringThe original CRON expression string
.CronTypeCronTypeSchedule type: CronType.Cron, CronType.Queue, or CronType.OneShot
.NextOccurrenceDateTimeOffset?The next scheduled date/time with local timezone offset
.StatusTaskStatusCurrent status: Scheduled, Running, Stopped, Failed, or Completed
.IsRunningboolTrue while the task is waiting for its next occurrence (Status = Scheduled)

Instance methods

MethodDescription
.Stop()Cancels the task, sets Status = Stopped, removes it from the global list

Static methods

MethodDescription
ScheduledTask.Remove(name)Stops a task by name same as Scheduler.Remove(name)
ScheduledTask.GetAll()Returns a snapshot of all registered tasks same as Scheduler.List()
// Inspect task state var task = Scheduler.Add("Daily", CronExpression.Parse("0 8 * * *"), (tName) => {}); print(task.Name); // "Daily" print(task.Status); // Scheduled print(task.IsRunning); // true print(task.NextOccurrence); // next fire time with offset // Stop by handle task.Stop(); // Stop by name ScheduledTask.Remove("Daily");
ScheduledTask.Remove(name) and Scheduler.Remove(name) are equivalent. Both stop the task and return true if found, false if not. Case-insensitive.
Scheduler Schedule CRON tasks and manage their lifecycle

The Scheduler namespace lets you register callbacks that fire automatically when a CRON schedule matches, on demand, or after a delay. All callbacks run synchronously on the calling thread via Tick() or WaitAll() no background threads, no thread-safety issues.

Methods

MethodReturnsDescription
Scheduler.Add(name, cron, callback [, tz]) ScheduledTask Schedule a recurring callback on a CRON expression. name is a unique identifier; cron is a CronExpression; callback receives the task name as first parameter: (tName) => { ... }. Optional tz (TimeZoneInfo) specifies the timezone for the CRON schedule (default: server local time).
Scheduler.AddOrUpdate(name, cron, callback [, tz]) ScheduledTask Add or replace a recurring task by name. If a task with this name already exists, it is stopped and replaced. Callback receives the task name as first parameter. Optional tz (TimeZoneInfo) specifies the timezone.
Scheduler.Enqueue(name, callback) ScheduledTask Fire-and-forget: runs the callback on the next Tick(). One-shot, then auto-removed. Callback receives the task name as first parameter.
Scheduler.Schedule(name, delayMs, callback) ScheduledTask Delayed one-shot: runs the callback after delayMs milliseconds, then auto-removed. Callback receives the task name as first parameter.
Scheduler.Schedule(name, dateTime, callback) ScheduledTask Delayed one-shot: runs the callback at a specific DateTime, then auto-removed. Callback receives the task name as first parameter.
Scheduler.ContinueWith(parentTask, childName, callback) void Registers a continuation: callback fires after parentTask completes successfully. Child callback receives the child task name as first parameter.
Scheduler.Remove(name) bool Stops a task by name (only if status is "Scheduled"). Returns true if found, false otherwise. Case-insensitive.
Scheduler.List() ScheduledTask[] Returns a snapshot of all currently active (Scheduled) tasks. Stopped/completed tasks are auto-removed.
Scheduler.Tick() int Fires any due callbacks now on the calling thread. Returns the number of callbacks fired.
Scheduler.WaitAll() void Blocks until all active tasks are stopped or completed. Drives callbacks on the calling thread.
Scheduler.Clear() void Removes all registered tasks.

ScheduledTask properties

PropertyTypeDescription
.NamestringUnique identifier (defaults to the CRON expression)
.CronExpressionstringThe original CRON expression string
.NextOccurrenceDateTimeOffset?The next scheduled date/time with local timezone offset, or null
.StatusTaskStatusTaskStatus.Scheduled, TaskStatus.Running, TaskStatus.Stopped, TaskStatus.Failed, or TaskStatus.Completed
.IsRunningbooltrue while the task is waiting for its next occurrence (status = Scheduled). false while running, stopped, failed, or completed.

Methods on ScheduledTask

MethodDescription
.Stop()Cancels the task, prints a trace, removes it from the global list
ScheduledTask.Remove(name)Static stops a task by name (same as Scheduler.Remove(name))
// Recurring CRON task callback receives task name Scheduler.Add("DailyReport", CronExpression.Parse("0 8 * * *"), (tName) => { print("Generating report for " + tName); }); // Fire-and-forget Scheduler.Enqueue("Notify", (tName) => { print("Immediate task: " + tName); }); Scheduler.Tick(); // Delayed Scheduler.Schedule("Reminder", 2000, (tName) => { print("2 seconds later: " + tName); }); // Continuation (runs after parent succeeds) var parent = Scheduler.AddOrUpdate("Backup", CronExpression.Parse("0 3 * * *"), (tName) => { print("Running " + tName); }); Scheduler.ContinueWith(parent, "NotifyBackup", (tName) => { print("Backup done " + tName); }); // List active tasks foreach (var t in Scheduler.List()) print(t.Name + ": " + t.Status); // Remove by name Scheduler.Remove("DailyReport");
Callback signature: All script callbacks receive the task name as the first parameter: (tName) => { ... }. The name is passed automatically by the scheduler you do not need to capture it yourself. All callbacks run synchronously on the calling thread via WaitAll() or Tick(). No background threads. Use WaitAll() for fire-and-forget scripts, or a custom Tick() loop when you need to stop tasks from outside callbacks.
SchedulerRunner High-level task runner with DB persistence, monitoring, and history

The SchedulerRunner class wraps Scheduler with SQLite persistence, automatic task loading, error tracking, execution history, and a monitoring loop. It is the recommended way to run scheduled tasks in production scripts.

Constructor

SignatureDescription
SchedulerRunner(sqlitePath, dbPath)Initializes the runner: loads the sqlite3 library, creates/opens the database, runs schema migrations

Public methods

MethodReturnsDescription
.Run() void Full lifecycle: print header → reset infinite tasks → seed demo tasks → load from DB → print next occurrences → fire due tasks → report infinite tasks → monitor → print history → clear. Enters a blocking monitoring loop until all tasks complete.
.Schedule(name, cronType, callback, cronExpr, tz) void Register a single task. cronType selects the schedule type CronType.Queue, .OneShot, or .Cron. The callback receives the task name. Parameters cronExpr and tz are only used for CronType.Cron.
.GetSqlitePath() string Returns the sqlite3 library path passed to the constructor
.GetDbPath() string Returns the database file path passed to the constructor

Usage examples

// 1. Full auto-run (seed + DB load + monitor) var runner = new SchedulerRunner("tools/sqlite3", "tasks.db"); runner.Run(); // 2. Schedule tasks directly via the public API var r = new SchedulerRunner("tools/sqlite3", "custom.db"); // Enqueue fires on next Tick, then self-removes r.Schedule("Notify", CronType.Queue, (tName) => { print("Sending: " + tName); }, null, null); // OneShot fires at next minute boundary r.Schedule("Report", CronType.OneShot, (tName) => { print("Generating " + tName); }, null, null); // Cron recurring every 5 minutes r.Schedule("Health", CronType.Cron, (tName) => { print("Check: " + tName); }, "*/5 * * * *", null); // Cron with timezone var tz = TimeZoneInfo.FindSystemTimeZoneById("Romance Standard Time"); r.Schedule("ParisTask", CronType.Cron, (tName) => { print("Bonjour " + tName); }, "0 9 * * *", tz);

Callback signature: (tName) => { ... } the task name is passed by the scheduler (via WrapNamedCallback), no closure capture needed.

REPL mode: When Script.IsRepl is true (a prompt is driving, not a file run), .Schedule() automatically calls Scheduler.Tick() after registering the task, so due tasks fire immediately. If pending tasks remain, a hint is printed inviting you to call runner.Run(false) to start the monitoring loop. In CLI mode, Run() handles Tick() in the correct lifecycle order.

Monitoring: Run() enters a blocking loop that calls Scheduler.Tick() every second. To build your own monitoring loop, call Scheduler.Tick() manually in a while loop after scheduling tasks with .Schedule().

Persistence: All task state (status, iteration count, timestamps, errors, elapsed time) is written to the SQLite database. On restart, Run() reloads unfinished tasks and resets infinite tasks that were completed/failed.

Script Runtime information about the script execution environment

The Script namespace describes the run itself: which directory it belongs to, whether a REPL session is driving it, and the interpreter behind it. Useful for adapting behavior in REPL vs CLI mode.

Members

MemberTypeDescription
Script.Directory()stringThe directory of the file being run, which is what a "./name" path is resolved against (see File). In the REPL it is the process directory. Empty when the run has no directory of its own. A callback has no current file: a request handler, a timer, an event handler or a feed.Start body runs later, on somebody else's turn, so Script.Directory() there answers the PROCESS's directory rather than the file's. Read it ONCE while the file is running and keep the value (var appDir = Script.Directory();), which is how the htmx board serves its own icon from wherever the engine was started.
Script.IsReplbooltrue when a REPL PROMPT is driving the interpreter. One thing sets it: the REPL mode itself. A direct CLI run (ScriptLangCore.exe script.slc) sees false, and so does a file run with .run from the prompt, because a file is not the prompt and its top level compiles exactly as a plain run's does. It previously followed .state, which made a .run file report true.
Script.InstanceInterpreterThe interpreter running the script, for a diagnostic that wants to identify the session, for example Script.Instance.GetHashCode().
// Skip seeding when running in REPL var runner = new SchedulerRunner("tools/sqlite3", "tasks.db"); runner.Run(!Script.IsRepl); // Conditional behavior if (Script.IsRepl) { print("Running interactively"); } else { print("Batch mode"); }
Script.IsRepl is set by the interpreter's REPL mode, which is how a script detects that a REPL session is driving it and skips one-shot seeding. A file run with .run from the prompt is in that mode; a script started from the command line is not.
These three members are the whole namespace, and a name it does not hold is refused with the list (Property 'X' not found in namespace 'Script' (it holds: Directory, Instance, IsRepl)). A run's failure is not one of them: it is a fact about the RUN rather than about the environment, so it is read from the value a run hands back, Result.HasError with Result.ErrorMessage and Result.ErrorInfo beside it. See Result, which is also what RunScript answers.

▼ Collections

array literal [...] Shorthand syntax for creating a native T[] array no new keyword needed

An array literal [1, 2, 3] creates a native T[] where T is inferred from the elements. Supports nesting, emptiness, indexing, foreach, and all array operations (.Length, not .Count).

var a = [1, 2, 3]; // int[] var b = ["a", "b"]; // string[] var c = []; // object[] (empty) var d = [1, "hello", 3.5]; // object[] (mixed) var e = [[1, 2], [3, 4]]; // nested arrays (int[][]) var f = [1.23m, 23.14m]; // decimal[]
var nums = [10, 20, 30]; print(nums.Length); // Result: 3 print(nums[1]); // Result: 20 nums[1] = 99; foreach (var x in [100, 200]) { print(x); } // inline iterable print(typeof(nums)); // Result: int[]
Element type inference: all-int → int[], all-string → string[], int+double → double[] (promoted), mixed types → object[]. To create a List<T> instead, use new List<T>().
Array literals in .NET method calls: When an array literal [a, b, c] is passed as a single argument to a .NET params method (e.g. Console.WriteLine("{0}", items)), it is treated as one object argument, not expanded into individual elements. The format placeholder sees the array itself (prints System.Object[]). To fill multiple format placeholders, pass each element as its own argument: Console.WriteLine("{0} {1} {2}", a, b, c).
dict literal { } Dictionary literal creates Dictionary

{ key: value, ... } creates a Dictionary like Python/JavaScript dicts. Keys can be any type (string, int, bool, etc.). Access and mutate with d[key].

A key is written as a bare name ({name: 1}, which is the STRING "name"), a quoted string, a single-quoted one-character key (which is a char), a number, or a bracketed expression. A literal is an EXPRESSION and never a statement, so {a: 1}; on its own line is refused with the two spellings that work: a declaration (var d = { a: 1 };) or parentheses (({ a: 1 });). A { that starts a statement is a BLOCK, which is what makes the bare form ambiguous.

var d = {}; // empty dict var d2 = {name: "Alice", age: 30}; // unquoted keys are strings d2["name"] // "Alice" d2[42] = "answer"; // non-string keys work too {[]: "array key", 0: "int key"} // expression keys [{}] // Dictionary<object, object>[]
// Create and use var cfg = {host: "localhost", port: 8080}; print(cfg["host"]); // "localhost" // Mutation cfg["port"] = 9090; print(cfg.Count); // 2 // Non-string keys var dk = {}; dk[42] = "int key"; dk[true] = "bool key"; print(dk[42]); // "int key" void check(string n, bool c) { if (c) print("OK " + n); else print("FAIL " + n); } // ContainsKey check if (cfg.ContainsKey("host")) { print("found"); } // Array as key (any expression works) var ek = {[]: "empty key", 0: "number key"}; // Dict in array typed as Dictionary<object, object>[] var da = [{}]; check("type", typeof(da[0]) == "Dictionary"); // Remove entry var dr = {x: 1, y: 2}; dr.Remove("x"); check("remove", dr.Count == 1);
Unquoted identifiers used as keys ({name: val}) are treated as string literals unlike regular expression context where they would be variable references. Use {"name": val} for quoted string keys (behaves identically).
Expression keys: Any expression can be a key, including arrays: {[]: "empty array key", [1,2]: "values as key"}. Numbers also work directly: {0: "zero", 1: "one"}.
Type inference: [{}] creates a Dictionary<object, object>[] the runtime type of the first non-null element determines the array element type. Mixed-type arrays fall back to object[].
comprehension [ for ] List comprehension transform and filter arrays with [expr for var in source if cond]

Comprehensions provide a concise syntax for creating arrays by iterating over a source collection, optionally filtering with if. The result is a native array (object?[]).

[expr for var in source] [expr for var in source if condition]
// Basic comprehension square each element var nums = [1, 2, 3, 4, 5]; var squares = [x*x for x in nums]; print(squares[0]); // 1 print(squares[4]); // 25 // With filter only even numbers var evens = [x for x in nums if x % 2 == 0]; print(evens[0]); // 2 print(evens[1]); // 4 // From a range literal var tripled = [x*3 for x in 1..5]; print(tripled[2]); // 9
Comprehensions work on arrays, lists, strings (iterating characters), and anything implementing IEnumerable. They do not create a lazy iterator the result array is fully materialized immediately.
List<T> Generic dynamic array ordered, indexable, growable

Creates a resizable list of elements of type T. Supports Add, Remove, indexing via [index], Count, ToArray, ToList, Sort, and all LINQ methods. Use new List<T>() for resizable lists; the array literal [1, 2, 3] creates a native int[] instead. list.ToList() returns a new typed copy a fresh List<T> with the same elements (copy semantics, like ToArray()); a List<int> typeofs as "List<int>".

Sort() sorts IN PLACE by the element type's own order, and Sort(fn) sorts through a comparable script function: (int a, int b) => { return a - b; } ascending, y - x descending, and any negative/zero/positive number means "before / same / after". The elements are written back through Add, so the element type is enforced exactly as it is for an added element, and a comparison that FAILS reports its own message (a y / 0 in the comparer says Division by zero, not the runtime's "Failed to compare two elements"). An ARRAY has the same member (see the array entry).

var list = new List<int>(); // resizable list var pre = new List<string>(1000); // explicit with capacity var seeded = new List<int>([1, 2]); // filled from a collection; each element is coerced, so a wrong one is refused var set = new HashSet<int>([1, 2]); // the same for a set, and a Dictionary from another dictionary var arr = [1, 2, 3]; // int[] (native array, not a List) var rows = new List<(string s, int i, bool b)>(); // tuple types are valid generic args rows.Add(("x", 1, true)); // Add validates arity + element types var grid = new (string, int)[] { ("k", 1) }; // tuple-typed arrays too
var nums = [1, 2, 3, 4, 5].ToList(); // List<int> with 5 elements (the array literal itself is an int[]) print(nums.Count); // Result: 5 var i = 0; while (i < 100) { nums.Add(i); i = i + 1; } print(Count(nums)); // Result: 105 // ToArray extracts all elements into a typed native array int[] here, not object[] var arr = nums.ToArray(); print(arr[0]); // Result: 1 // ToList copies into a fresh typed list List<int> here var copy = nums.ToList(); print(typeof(copy)); // Result: List<int>
Dictionary<K,V> Key-value map with fast lookup Keys(), Values(), indexing

Creates a dictionary mapping keys of type K to values of type V. Keys are unique. Supports ContainsKey, Keys(), Values(), indexing via [key], and all LINQ methods.

Tuple keys use value equality: two distinct tuples with equal scalar/string/nested-tuple elements are the same key (so d[(1, 2)] finds a key stored as a separately-created (1, 2); numeric widening applies, e.g. (1L, 2L) aliases (1, 2)). Elements that are arrays/lists/dicts/objects keep reference identity. The ==/!= operators on tuples are unchanged.

Iteration: foreach over a dictionary yields KeyValuePair objects, and KeyValuePair(key, value) builds one (the same bare-call shape Rect(l, t, r, b) has, since a bare new KeyValuePair(a, b) reaches the CLR generic and cannot infer its type arguments) with .Key and .Value properties. This works on both native Dictionary<K,V> and the boxed rows from Sqlite.Query.

var d = new Dictionary<string, int>(); var pre = new Dictionary<string, int>(500);
var d = new Dictionary<string, int>(50); d["key"] = 42; print(d["key"]); // Result: 42 print(Count(d.Keys())); // Result: 1 // Iterate with foreach yields .Key and .Value foreach (var kv in d) { print(kv.Key + " = " + kv.Value); } // Keys() and Values() return arrays (O(1) bulk copy) var allKeys = d.Keys(); var allVals = d.Values();
KeyValuePair A key and its value, as one object what a dictionary iteration yields

A single key-value row: .Key and .Value. A foreach over a Dictionary yields these, so the common way to hold one is to receive it; KeyValuePair(key, value) builds one when a script needs to make its own. typeof answers "KeyValuePair" and is KeyValuePair is true.

.Value holds anything: a number, a string, a tuple, a list, or null. A tuple value is read by index (.Value[0]) or by the CLR element name (.Value.Item1), and it still travels inside a List<KeyValuePair<string, object>>.

Build it with the BARE CALL, not new: a bare KeyValuePair name resolves to the CLR generic, whose constructor takes (TKey, TValue) and cannot infer them from the arguments, so new KeyValuePair("a", 1) refuses. KeyValuePair(key, value) is the shape Rect(l, t, r, b) has. A wrong arity is refused by name: KeyValuePair expects 2 arguments: key and value.

A pair answers Dispose() as a safe no-op (so using and is IDisposable behave uniformly), and printing one shows the type name rather than its contents; Json.Serialize is what shows the contents.

var kv = KeyValuePair("alpha", 42); print(kv.Key + " = " + kv.Value); // alpha = 42 print(typeof(kv)); // KeyValuePair print(kv is KeyValuePair); // True // A tuple as the value, read both ways: var packed = KeyValuePair("row", (1, 2, "three")); print(packed.Value[0]); // 1 print(packed.Value.Item3); // three // And it travels in a typed list: var rows = new List<KeyValuePair<string, object>>(); rows.Add(packed); print(Count(rows)); // 1 // The usual way to hold one is to receive it: var d = new Dictionary<string, int>(); d["a"] = 1; foreach (var item in d) { print(item.Key + " = " + item.Value); } // a = 1
HashSet<T> Unordered collection of unique elements with O(1) lookup

Creates a hash set of elements of type T. Duplicates are silently ignored. Supports Add, Remove, Contains, Count, Clear, ToArray, ToList, foreach, and all LINQ methods. Use new HashSet<T>() for a mutable set; there is no literal syntax. With tuple elements (HashSet<(int,int)>) duplicates are detected by value: two distinct tuples with equal scalar/string/nested-tuple elements count as the same element (numeric widening applies); composite elements keep reference identity.

set.ToList() returns a new typed copy a fresh List<T> (a HashSet<int> .ToList() is a List<int>); the element order follows the set's iteration order, which is undefined.

var set = new HashSet<int>(); var pre = new HashSet<string>(1000); // explicit capacity
var ids = new HashSet<int>(); ids.Add(42); ids.Add(99); ids.Add(42); // ignored already present print(ids.Count); // Result: 2 print(ids.Contains(42)); // Result: True print(ids.Contains(1)); // Result: False ids.Remove(99); print(ids.Count); // Result: 1 // Iteration via foreach foreach (var x in ids) { print(x); } // ToArray extracts elements into a typed native array int[] (order is undefined) var arr = ids.ToArray();
Order of elements in a HashSet<T> is not guaranteed and may change between runs. Use List<T> if insertion order matters. HashSet<T> is backed by System.Collections.Generic.HashSet<T> and uses the default equality comparer for the element type.

▼ UI Subsystem (Win32)

Application Win32 application create forms, dialogs, message loop

Application provides the Windows message loop, form creation, and file dialogs. Use Application.Run() to start the GUI message loop.

Properties

FilePathFull path to the RUNNING executable (e.g. D:\...\ScriptLangCore.exe). In an EMBEDDED run that is the HOST's exe (ScriptLangCore.Launcher.exe or a packaged app), while Path is the engine's own folder, so the two can name different directories: a script that wants to spawn "the same program again" asks FilePath, and one that wants the engine's assets\ asks Path.
PathDirectory path of the running executable (e.g. D:\...\bin\Release\net11.0). An EMBEDDED run reports the folder of the ScriptLangCore.dll it loaded instead, which is where the engine keeps its own files (see Where the engine is when it is embedded).
DataPathWhere a program may WRITE, which is not where it runs. An installed engine keeps its folder under Program Files, where a normal account can only read, so a file saved beside the executable fails there. This is the install's own data folder (the installer creates it and grants Modify to the built-in Users group), or a declared SLC_DATA_HOME, which wins. Which folder that is follows the layout: the engine folder's own data in a repository or published tree, and {app}\data BESIDE {app}\bin in an installed one. It answers a PATH and nothing else: create it (Directory.CreateDirectory(Application.DataPath)) before the first write, and ask Application.DataWritable() whether that will work. A database, an upload folder, a run store or a build output belongs here rather than beside the executable.
ExeIconThe running executable's own icon, as a handle, out of its resource (the project's ApplicationIcon). This is what a form takes when the script assigns none; 0 when the build has no icon resource.
ArgsWhat the executable was invoked with, as a list of strings, with the executable's own path left out: the list a C# Main(string[] args) receives. So ScriptLangCore.exe app.slc --flag gives ["app.slc", "--flag"], which is why a script's own flags start at [1] there. The list is rebuilt on every read, so editing the one you were handed does not change what the next read reports. A run started from a session carries its own: .run tool.slc -- a b makes Application.Args ["tool.slc", "a", "b"] for that run only, and the session's own list is back afterwards.
CurDirRead and write. The PROCESS's current working directory, which is the directory a BARE relative path resolves against: after Application.CurDir = "data", File.ReadAllText("x.txt") reads data\x.txt, while a path that starts with ./ still means "beside this script" and is untouched (see the path rule in the File entry). Assigning refuses a value that is not a string, and a directory that does not exist, naming what arrived (Application.CurDir must be a directory path, not 'int', Directory not found: 'X:\nope'). Directory.GetCurrentDirectory() and Directory.SetCurrentDirectory(...) are the same two operations spelled as methods.
SingleInstanceRead and write, default false. One application, the way VB's IsSingleInstance means it, with two effects. IN PROCESS, Application.CreateForm(title) answers the form already carrying that title instead of building a second window, so a snippet pasted twice reuses its panel. ACROSS PROCESSES, turning it on takes a named lock for this run's script, so a SECOND run of the same file ends at the assignment rather than building a second set of windows: it logs ONE line at ERROR level (SingleInstance: already running in another process, so this run ends.) and exits with ExitCode.Refused (3), which a launcher can tell from a genuine failure (1). The lock's name is appended to that line only when the SINGLE_INSTANCE diagnostic is on (SLC_SINGLE_INSTANCE=1), because it is a sanitized full path. Windows releases the lock when the first run's process ends. It takes a boolean and nothing else (SingleInstance takes true or false, not 'int'), and false releases the lock. Set it at the TOP of a script: the assignment is where both effects begin.

Where the engine is when it is embedded

A script normally runs inside ScriptLangCore.exe, so Application.Path is the executable's own folder. An EMBEDDED run is different: a host loads ScriptLangCore.dll and may keep that DLL anywhere, and then Application.Path reports the folder the engine came from, because that is where the engine's own assets\, tools\ and sqlite3.dll were published. The shipped launcher finds the DLL in four steps, and the first hit wins:

StepWhat it looks for
SLC_ENGINE_DLLthe FILE named by that environment variable
beside the exethe host's own folder, which is the shape a packaged app uses, and a copy here WINS over the two steps below
SLC_ENGINE_HOMEthat DIRECTORY, holding ScriptLangCore.dll
PATHeach directory in its own order, first hit wins

A copy beside the exe comes before the environment on purpose: an INSTALLED engine declares SLC_ENGINE_HOME for every process on the machine, so an app that ships its own engine would otherwise run the installed one and silently change version. A declared location is OBEYED rather than consulted: when nothing is beside the exe and SLC_ENGINE_HOME names a folder without ScriptLangCore.dll, or SLC_ENGINE_DLL a missing file, the launcher refuses and names what it was told instead of falling back to another copy, so a typo can never load a different engine than the one you named. A host of your own decides this for itself, since the host is what loads the DLL; what a script can rely on is that Application.Path is the folder of the engine it is running in, while ./ and Script.Directory() keep naming the file being run, and Application.CurDir the process's working directory.

Application methods

InputBox and CreateInputBox have a section of their own, since a prompt carries a good deal more than a method signature: see InputBox.

DataWritable()Whether Application.DataPath really accepts writes, PROVEN rather than assumed: it creates a uniquely named SUBFOLDER there, writes a file inside it, and removes both, so a folder that allows a file but not a folder answers false. That distinction is the one an upload folder, a per-run work directory or a build output needs, and it is why a plain file probe is not enough. The answer is taken once per process. false is not an error, it is a cue to fall back: %LOCALAPPDATA%\ScriptLangCore always exists for the account that is running.
CreateForm(title [, configure])Create a new Form object with its native window already made, and hidden: form.Created is true at once while form.Visible stays false until Show(), so every control and item can be built before the form appears (form.SetMenu(bar) works there too). A TITLE IDENTIFIES THE WINDOW when Application.SingleInstance is on: a repeat answers the form the script already has (with a warning naming its handle) instead of a second window. With it off a repeat still creates the second window and WARNS about the duplicate title, which is what a pasted-twice snippet used to leak silently.
FindForm(title)The form this run already has under that title, or null: the other half of CreateForm, and the question form.Created cannot answer (that one says whether the instance you hold has a window, not whether the form existed before). It is what makes a startup idempotent without an exception: var p = Application.FindForm("panel"); if (p == null) { p = Application.CreateForm("panel"); ...init... } runs the init once however many times the snippet is pasted.
MonitorCount()How many monitors this machine has, so a script can pick one: form.Screen takes 0 .. MonitorCount() - 1 and refuses anything else by name.
ThemeActive()1 when this machine is running with visual styles, else 0. Ask it BEFORE drawing a themed part: e.ThemePart answers -1 when there is no theme.
CursorPos()The mouse position in SCREEN coordinates, as [x, y]. A posted message cannot move it, which is what makes it the stable reference a drag wants.
MessagePos()The screen position carried by the message being handled (a packed x/y in one value).
ForegroundWindow()The handle of the window the user is currently on, or 0.
WindowFromPoint(x, y)The handle of the window at a SCREEN point, or 0. Useful for a hit test the engine has no member for.
AsyncKeyState(vk)1 while a virtual key is down, else 0. It reads the key AT THE CALL, so it is how a drag asks about the left button without assuming the event carried it.
SystemMetrics(index)A system metric at the SYSTEM dpi (SM_CXSCREEN is 0, SM_CYSCREEN 1).
SystemMetricsForDpi(index, dpi)The same metric measured for a given dpi, which is what a scrollbar or a frame size has to be asked for on a per-monitor box.
AdjustWindowRectExForDpi(rect, style, menu, exStyle, dpi)Grow a client RECT (a Mem buffer) into the window rect its frame needs at that dpi. It writes back into the buffer and answers 1 on success.
SetProcessDPIAware()Tell Windows the process scales itself. The engine asks for per-monitor v2 where it can, so this is for the rare host that must be told early.
GetPixel(x, y), GetPixel(dc, x, y)The pixel at a SCREEN point, for anything outside a window's client: a caption, a scrollbar, another process's window. A control's own client is ctrl.GetPixel(x, y), which takes client coordinates. The reading is a COLORREF, so Colors.FromPixel(...) turns it back into a colour. With two arguments the dc is opened and closed around the one read; with three it reads through a dc the script holds, which is what a sweep over hundreds of pixels wants.
GetDC(), ReleaseDC(dc)The screen dc those reads can share, and the call that hands it back. Hold one across a loop instead of opening one per pixel.
FormToJson(host [, options]), FormFromJson(doc)A HOST as a stored TEMPLATE, where a host is a form, an MDI frame or an MDI document window: the first writes the document (the same one Json.Serialize(host) writes, and it takes the SAME options as the serializers, so {"pretty": true}, a bare option name or a JSON text of them all work), and the second builds a NEW host from it, WHICHEVER its root Kind names: a Form, an MDI frame (with its document windows) or a document window (which gets a frame of its own to be parented to). This is the pair a database of forms is read and written with: one row holds the document, and a form comes back out of the row.
CreateMdiForm(title [, configure])Create a new MDI frame (MdiForm), with an optional trailing configure callback like CreateForm's.
CreateChildMdiForm(title, parentForm [, configure])Create an MDI frame embedded in a parent Form, with an optional trailing configure callback like CreateForm's.
Run([form] [, tabIndex])Start the message loop, which runs until the LAST form closes. It waits on the forms this run has shown: a form created with Application.CreateForm() and never shown does not keep the loop alive (its window exists from creation, so waiting on mere existence would wait for ever), which also means Run() with nothing shown returns at once. A form passed here is shown first, and it takes the window that owns the focus, so a child of it can be focused without a click. The control that gets the focus is the first in TAB ORDER, or the one whose TabIndex is given here: Run(form, 2) opens onto that stop, and Run(2) asks the same of a form that is already running, so a script does not have to keep a form to be understood. A form with no stop that can take the focus keeps the focus it has.
RunFor(timeoutMs [, form])The same loop with a DEADLINE: after that many milliseconds every open form gets a WM_CLOSE, so a demo or a screen ends itself instead of needing a hand-rolled timer. It posts the CLOSE rather than calling Close() on purpose, so a form's Closing handler can still REFUSE and keep the application up. It is a name of its own because Run(number) already means "take the focus to that TabIndex".
Quit([code])Post WM_QUIT to stop the message loop, carrying a CODE to the process when one is given: Application.Quit(7) leaves 7. With no code the process keeps the one it has, which is 0 unless the script set another, so this is not a second spelling of exit(n): that one ends the SCRIPT where it stands, unwinding and running finallys, while this ends the LOOP and lets the script carry on the message loop.

File dialogs

CreateOpenFileDialog()Returns an OpenFileDialog with properties Title, Filter, InitialDirectory, and method ShowDialog() returning 1 (OK) or 2 (Cancel). On success, FileNames[0] contains the selected path.
CreateSaveFileDialog()Returns a SaveFileDialog with same properties plus DefaultExtension. On success, FileName contains the selected path.

Message loop control

IsRunning()Returns true while the message loop is active.
PeekMessage()Non-blocking returns a MessageInfo or null.
WaitMessage()Blocking waits for a message, translates and dispatches it, then returns a MessageInfo. The MessageInfo it answers carries Hwnd, Message, WParam, LParam and Time, and DECODES the packed halves a message is built from: msg.LowWord(msg.WParam) is the id in a WM_COMMAND and msg.HighWord(...) its notification, with msg.LowByte/msg.HighByte for the 8-bit form; msg.MakeLong(lo, hi) and msg.MakeWord(lo, hi) build a value to post back.
DispatchMessage(msg)Dispatch a previously peeked message.
DoEvents()Process pending messages without blocking.
ShowConsole(true); var f = Application.CreateForm("Demo"); f.Theme = ThemeMode.Dark; f.Width = 400; f.Height = 300; f.CreateButton("Click me", 10, 10, 100, 30); Application.Run(f);

The same form with the configure callback, which is the other spelling of every line above (they can be mixed freely, and a script that builds many controls reads better this way):

ShowConsole(true); var f = Application.CreateForm("Demo", (frm) => { frm.Theme = ThemeMode.Dark; frm.Width = 400; frm.Height = 300; frm.CreateButton("Click me", 10, 10, 100, 30); }); Application.Run(f);
Full example: assets/language/ui/demos/rich_editor.slc
Form Window object container for managed controls

Created via Application.CreateForm(title), which builds the native window at once and keeps it hidden: Created and Handle are true immediately, Visible stays false until Show(), so the whole form is built while nothing is on screen (every control, the items in a list, a menu bar, the event handlers, the theme) and the window appears once, complete. It provides factory methods for all managed controls and event handlers for user interaction. All controls are automatically parented to the form and receive dark mode coloring via WM_CTLCOLOR* messages.

Properties

form["ChildControlName"]The CHILD control carrying that name, or null. The index is a CHILD's name and never the form's own, which is form.Name and is what its caption is built from. It is the handle a document's names are FOR: a document carries the look rather than the behaviour, so re-attaching behaviour means reaching a child by the name it gave it. It works the same on a Form, an MdiForm and an MdiChild, because the index IS the one lookup they share. The name follows the interpreter's own case rule, like every other name, and the first match wins where a script has given two controls one name. Indexing is the ONLY spelling: Find(name) was retired once the index covered it. A miss is loud rather than silent: form["typo"].Text is refused as Cannot access property 'Text' on null, with the position, so a name rebuilt at run time cannot quietly do nothing. ?. is the null-safe way to READ one (form[n]?.Text answers null on a miss), but it is refused as an ASSIGNMENT target (form[n]?.Text = "x" is a parse error), so re-attaching is a guard: var b = form[n]; if (b != null) b.Click = (...) => { ... }; (a ?. FURTHER OUT in a target is IGNORED rather than refused, which is not protection: see the ?. entry). A non-string index is refused by name rather than coerced, and a WRITE (form["x"] = c) is refused: a control is reached by name, never replaced by one.
ThemeA ThemeMode, so it is written form.Theme = ThemeMode.Dark: Light or Dark for the two native looks, System to follow Windows' own app-mode setting, and Custom to paint the palette below. Reading DarkMode answers the effective leg, which for Custom follows the palette background's brightness.
ThemeBackground, ThemeText, ThemeBorder, ThemeSelection, ThemeDisabledThe colours a Custom form paints with, written 0xRRGGBB. A colour left unset comes from the effective leg, a control's own BackgroundColor/TextColor still wins, and a part the engine does not draw (a scrollbar, a themed button face) follows the palette background. Changing one re-applies the theme to the form and to every control, so a palette can be adjusted while the window is up.
Width, Height, Left, TopWindow position/size. A width or height written BEFORE the form is shown is a DESIGN measurement in the system DPI's units, so the same number is the same physical size on a 100% and a 150% monitor (900 renders 900 px on the reference monitor and 600 px on the other); after Show() a write is a live size in pixels.
StartPosition0 = manual, 1 = center screen, 2 = center parent. 1 is applied when the window APPEARS (the first Show()) and against the size it then has, so the order of this assignment and of Width/Height does not matter; it also centres a form whose window already exists as soon as it is assigned.
CloseBox, MaximizeBox, MinimizeBox, Resizable, Modalbool the four window-style properties (CloseBox, MaximizeBox, MinimizeBox, Resizable) default to true and toggle the close box (the system menu and the X in it), the maximize and minimize boxes, and the thick (resizable) frame: set them any time before Show(), since each applies a style bit to the window Application.CreateForm already made and a form with no close box is still closable from a script with Close(). Modal is the odd one and defaults to false: it is not a style but an instruction to Show(), which then DISABLES this form's owner while the form is up and restores it when the form dies, so dlg.Modal = true; dlg.Show() is how a dialog owns its caller and dlg.Close() releases it.
Screenint, 0-based in the order Windows enumerates the monitors (the one Windows calls DISPLAY1 is 0). Assigning it BEFORE Show() is what makes a form OPEN on that monitor: the window is not created yet, so the request is honoured where it is created instead of the form appearing somewhere else and jumping. Assigning it later moves the form, centred in that monitor's work area with its size untouched. A value with no monitor behind it is refused, naming how many exist; Application.MonitorCount() is that count.
Paddingint, the space the DOCK layout keeps between the window's edge and the controls it places (DockStyle.Left, .Top, .Right, .Bottom, .Fill), so a docked box's scrollbars do not sit on the window's border. Zero by default; a control positioned absolutely ignores it; the value scales with the DPI like every other design measurement. A control's own Margin then REPLACES it on the sides that control names, which is documented with the controls.
GridSize, GridColorA designer grid drawn by the form itself: GridSize is the dot spacing in client pixels (0 or 1 = no grid) and GridColor the dot colour. The dots are drawn before any Paint handler, and the form clips its children, so a placed control is never overpainted.
HandleThe underlying HWND (IntPtr, accessible as long in scripts).
CreatedWhether this instance already has its native window, which is the question Handle != 0 answers spelled in one word. A FORM's window is created with Application.CreateForm() (hidden), so a form reports true from the moment you hold it and its controls and their items can be built before Show(); form.Visible is the question "is it on screen", which stays false until Show(). A child control reports true once it has been constructed. It says nothing about WHO created the form: a form answered by a repeated Application.CreateForm is a real form, so it reports true as well. Ask Application.FindForm(title) for "does this form exist already".
ControlsThe controls this form holds, in the order they were created. form.Controls.Count is how many and form.Controls.Get(i) is the one at index i, refused with the range when i is past the end. An MDI frame or child holds a plain list, so Controls.Count reads the same there: one spelling for both.

Form methods

SetIcon(icon, [size], [color])Set the window's icon, in one spelling for three cases. A CHARACTER is rendered into an icon: form.SetIcon("✅") draws it at 32 px in the colour the host needs (white on a dark form, near-black on a light one, re-rendered if DarkMode changes), form.SetIcon("✅", 48) picks the size, and form.SetIcon("✅", 32, 0x1F7A1F) the colour, written 0xRRGGBB. A NUMBER is an icon handle the script already has, Application.ExeIcon being the one the engine hands out, with 0 meaning no icon at all; the size and the colour apply to a rendered character, not to a handle. A form nobody sets one on takes the RUNNING EXECUTABLE's own icon, in both sizes. The size is checked before anything changes, so a refused call leaves the window as it was, and a character no font covers leaves it with the icon it had. Set before Show(), it is applied where the window is created, so nothing flickers. Returns the handle the window now holds, which is how a script reads the icon back.
AdoptChild(hwnd, insetL, insetT, insetR, insetB)Parent a foreign child window (e.g. the HWND returned by Com.HostActiveX) into the form, turn it into a real child (WS_CHILD, clears WS_POPUP) and keep it fitted to the client area minus the insets re-applied automatically on every WM_SIZE. hwnd is the long handle from HostActiveX.
Show()Create the window handle (if not already created) and display the form on screen.
Activate()Be the window the user is looking at: the thread's ACTIVE window, the z-order and the desktop foreground, which are one thing and are what a click used to supply. Show() does this too, so a script calls it to raise a window it already has. A window that does not exist yet is left alone.
InitHandle()Make sure the form has a window while leaving it invisible. A form from Application.CreateForm already has one (created, hidden), so this is an idempotent no-op there and a script does not need it; it is the named way to say "a hidden window must exist" for an object that has none yet (the engine's own dialogs use it). The script pattern is build the form and its controls, then Show().
Quit([code])Close the form AND end the run: it does what Close() does, then stops the message loop (WM_QUIT), so Application.Run returns even when other forms are still up. With a CODE the process leaves with it, exactly as Application.Quit(code) does: form.Quit(5) leaves 5, measured on the shipped build. Close() alone is the window, which ends the loop only when it was the last form.
Close()Send WM_CLOSE to the form. Triggers the Closing event set e.Cancel = true to prevent closure.
SendMessage(msg, wParam, lParam)Send a window message to the form's own window and return the message's result. The same operation ctrl.SendMessage performs on a control, so no .Handle is needed.
PostMessage(msg, wParam, lParam)Queue the message to the form's window and answer whether it was queued, without waiting for it to be handled. The same operation ctrl.PostMessage performs on a control.

Control factory methods

These build a control and hand it back, and they belong to the FORM because the form is what holds it: a control cannot make a sibling. The kinds they return are described in the Controls entry, which is about the controls themselves.

Every one of them takes an optional trailing configure callback, and so does Application.CreateForm (and the two MDI hosts). The callback runs on the thing the factory just made, AFTER it was parented and given its window, and the factory still returns that same instance. The two spellings are equivalent, and they mix freely; the callback one says "create and finish this" in one statement, which is what a form with many controls reads best as:

// the form itself takes the callback too, so the whole window is one statement var form = Application.CreateForm("player", (frm) => { frm.Width = 520; frm.Height = 240; frm.Theme = ThemeMode.Dark; }); // the statement-by-statement spelling of two controls var btn = form.CreateButton("OK", 10, 10, 100, 30); btn.Enabled = false; btn.Click = fun(Control sender) { print("ok"); }; var list = form.CreateListBox(8, 50, 220, 120); list.AddItem("one"); list.SelectedIndex = 0; // the same two controls, created and finished in the statement that makes them form.CreateButton("OK", 10, 10, 100, 30, (b) => { b.Enabled = false; b.Click = fun(Control sender) { print("ok"); }; }); form.CreateListBox(8, 50, 220, 120, (l) => { l.AddItem("one"); l.SelectedIndex = 0; }); form.Show();

Four rules it keeps. It runs after the control is adopted, so .Handle is real and form.Controls already holds it. Its parameter is the concrete type (CheckBox, ListBox, Form), so a cast is never needed. A form's callback runs only on a form that call created, never on a reused one (with SingleInstance on, the second CreateForm hands the first window back and its callback does not run again: use Application.FindForm for a get-or-create). And an argument that is not callable is REFUSED by name rather than ignored.

ScrollBar = true gives a control the engine’s own NARROW bar. Windows paints a native scrollbar in the theme’s colours and offers no supported call to change them (measured on five theme variants, all the light 0xF0F0F0 face), so a dark form read its bar as a white stripe. With ScrollBar the native bar is not asked for at all: the engine draws a strip about 45% of the native width, in the host’s background with a blended thumb, keeps the text off it with EM_SETRECT, and drives the control itself: a click in the track pages, the wheel moves three lines, the thumb can be dragged, and the pointer over the strip is not the class’s own cursor (a RichEdit gives its whole client an I-beam, and the strip lives inside it): the THUMB takes the hand, the track the plain arrow, and the text keeps its I-beam. Supported on a multiline EDIT and a RichEdit; any other control is refused by name. The window must be created WITHOUT WS_VSCROLL: a class puts that bit back once it has one, so the setter refuses a window that already carries a bar and names the fix. A multiline EDIT/RichEdit also turns WS_VSCROLL on and off by itself from its content, which is why a native bar disappears while the text fits.
CreateLabel(text, x, y, w, h)Label static text.
CreateButton(text, x, y, w, h)Button clickable with .Click event.
CreateTextBox(text, x, y, w, h), CreateRichTextBox(text, x, y, w, h)TextBox is a single-line or multi-line EDIT with a .Text property; RichTextBox is the class that formats each RUN, which is what a coloured log needs, and it WRAPS by default (a rich text box is read rather than typed into, and a long line has no horizontal bar to reach its end): a RichEdit takes its wrap when its window is CREATED, so set .WordWrap before the control is shown. .WindowClass answers the class it really got (RICHEDIT50W, RichEdit20W, or EDIT when neither library is there), which is what a tool reports or checks before it colours a run. The rich one picks its own Windows class once per process (RICHEDIT50W from msftedit, RichEdit20W as the fallback, EDIT last) and both take .WordWrap.
CreateCheckBox(text, x, y, w, h, [checked])CheckBox toggle with .Checked property.
CreateRadioButton(text, x, y, w, h, [checked])RadioButton mutually exclusive option.
CreateListBox(x, y, w, h)ListBox scrollable list with AddItem(), SelectedItem, SelectedIndex.
CreateComboBox(x, y, w, h)ComboBox dropdown list with AddItem(), SelectedItem.
CreateTrackBar(x, y, w, h)TrackBar slider with Minimum, Maximum, Value and an assignable .Scroll handler (fires on user drag).
CreateTreeView(x, y, w, h)TreeView hierarchical tree with InsertItem(text, parent, insertAfter), Expand(item, expand), SelectedItem, GetItemText(item). Note: InsertItem has a struct marshalling issue on x64 items return valid handles but TVM_GETCOUNT may report 0.
CreateListView(x, y, w, h)ListView tabular grid with InsertColumn(index, text, width), InsertItem(index, text), SetItemText(row, col, text), ItemCount, DeleteItem(index), BeginUpdate() and EndUpdate(). Created double buffered, and a refill costs one repaint when it is wrapped in BeginUpdate() / EndUpdate(). Fill it in place with ItemCount to overwrite the rows that exist and DeleteItem for the tail, rather than clearing first: a cleared list is a state the screen can show, so refresh it when its rows actually change rather than on every interaction.
CreateStatusBar(x, y, w, h)StatusBar bottom status pane (_partWidths={-1} fills width, SB_SETBKCOLOR sets dark background).
CreateTabControl(x, y, w, h)TabControl tabbed panel with AddTab(text). Adding a tab and letting the message pump run both work: a tab control made this way reports TCM_GETITEMCOUNT = 2 after two AddTab calls and survives the dispatch the old note here warned about, so the raw SysTabControl32 workaround is retired.
CreateDateTimePicker(x, y, w, h)DateTimePicker date picker control.
CreateToolBar(x, y, w, h)ToolBar common control toolbar.
CreateSysLink(text, x, y, w, h)SysLink hyperlink control.
CreateHotKey(x, y, w, h)HotKey hotkey input.
CreateRebar(x, y, w, h)Rebar rebar container.
CreateWinControl(className, text, x, y, w, h, [style], [exStyle])GenericControl any Win32 class via CreateWindowExW. Registered in Controls collection.

Quitting, and what each call does to the other windows. The two verbs are not the same act: one stops the RUN and one stops a WINDOW, and only a form you close yourself goes away.

callwhat it closesthe exit code
Application.Quit([code])Nothing. Every form you opened is still standing when Run returns, with its window intact, and closing them stays your script's job.code, when it is not 0. This is the code the process leaves with if the script then ends normally.
form.Quit([code])That form only, exactly as its Close() does. Any OTHER form is still up and the run has ended, so its window outlives the loop.code, when it is not 0.
form.Close()That form only. The run ends when it was the LAST form, which is why a Close on one of several leaves the loop pumping.None: the process keeps the code it already has.

A 0 is deliberately not assigned, so it cannot force the process back to 0 once a non-zero code is set: use a real code, or exit(0), which is the script's own verdict. With several quits in one run the LAST one posted is the one that survives, because the loop drains what is left of its queue on the way out. To close two windows and leave one code, close both and quit once: a.Close(); b.Quit(7);

form.Theme = ThemeMode.Dark; form.StartPosition = 1; // Center form.CreateLabel("Name:", 20, 20, 60, 25); form.CreateTextBox("John", 90, 20, 200, 25); form.CreateButton("OK", 200, 100, 60, 25);
Controls What every control shares, the kinds a form creates, and the styles, messages, tooltips and events they answer

Every control comes from a factory on its form (form.CreateButton(...)) and each one is a window the engine wraps, so the members below are shared by all of them, the form included. What is NOT here is what a single kind has on its own: a Checked, an AddItem(), a Minimum, the cell members of a ListView. Those are named in the factory row below and in that kind's own entry.

Every control the factories return comes up carrying WS_TABSTOP, and Tab and Shift+Tab move the focus between them IN TABINDEX ORDER: the engine answers those two keys itself, before a key can reach a control and become a character in it, which is what a Tab used to be inside a multi-line input. The order is sorted by TabIndex with ties following the order the controls were added, and it SKIPS anything that cannot take the focus (not a tab stop, disabled, or hidden, the last two asked of the window so a disabled or hidden parent counts). A control that becomes a tab stop is FOCUSED as well, which is what makes the change visible, and the focus cue is turned back on with it, since Windows hides that cue after mouse input. A label is the one exception: a STATIC takes no focus, so Tab has nothing to stop on there. A Form is not one either, and that is not a choice: WS_TABSTOP is the same bit as WS_MAXIMIZEBOX, so a form given one grows a maximise box.

Every control also carries an Id: unique in the process, assigned as its window is created and carried as the window's own child id, so WM_COMMAND reports it and form.GetId(id) finds the control by it. GetId() is the same value as a method, and GetId(id) is the control BEHIND an id, so form.GetId(15).Handle reaches a control a script built dynamically without keeping its handle anywhere. An id no live control carries answers null.

Members every control shares

GetId(), GetId(idOrHandle)The control's own ID, the same value as a method, and the control BACK from EITHER a number or a window: form.GetId(15).Handle and form.GetId(btn.Handle).Handle reach the same control, so a script never has to know which of the two it holds. An id is asked of the window first (the Win32 way) and a handle is answered by the engine's registry, where a handle is unique in the process. The id IS the window's Win32 child id, read live FROM the window, so a script that assigns one itself with SetWindowLongPtr is not a second mechanism. It belongs to CHILD windows: a Form's own id is 0, because GWLP_ID is the low word of the slot a top-level window keeps its menu handle in. Auto ids start at 0x8000, above the ids Win32 reserves (1 is IDOK) and the range a resource editor hands out; 0 is a window that does not exist yet, a number nothing carries, or one that has no child id at all.
ClassHandlesMouseSet true when this control's own Windows class must see its mouse messages first, which the engine steps aside for: it takes no capture on the press and does not forward them to the script handlers. The engine already does this for the classes it knows (a ListBox, a TrackBar, a DateTimePicker and the rest, because taking the capture cancelled what they had pending), so this is the same rule for a class that list does not name. Default false, which is the engine's normal handling.
SetMenu(menu)Wear a MENU as this window's bar, and the id of the item that fired, read inside the Command handler. The Menu type itself is its own entry below, with the items, the submenus and the popups.
MessageBox(text [, caption] [, type])Say something on THIS window, owned by it. With no window to own the box, the BARE global MessageBox(text [, caption] [, type]) is the same call with a null owner, which is what a tool that has no window prompts with; it is not on a namespace because nobody owns it. A message box wants an owner's handle and a control already holds one, so the receiver IS the owner: form.MessageBox("Saved", "Status") is the whole call, with the plumbing done. The typing matches the handle-taking spelling, TYPE flags included (1024 is MB_SYSTEMMODAL), and the return is the button the user chose.
Invalidate([x, y, width, height]), InvalidateUnion(x1, y1, w1, h1, x2, y2, w2, h2)Mark the control for REPAINTING. With no arguments the whole client, which is what a script that changed a drawing asks for; with the four numbers, just that rectangle, in client coordinates. InvalidateUnion takes two rectangles and invalidates the union, which is the drag shape: the only pixels that can have changed are where the control WAS and where it IS. A three-argument form takes the old origin and an OBJECT, and reads X, Y, W and H off it by name: the caller knows where the thing was, and the thing knows its own place and size. The engine owns the arithmetic, so a caller does not compute it, and the two are the reason a drag does not repaint a form's whole grid and flicker.
WindowRectThe window's OWN rectangle, which is what the control BECAME rather than what was asked for: Left/Top/Width/Height are the request, and the two differ whenever the engine adjusted it.
ClientRect, ClientWidth, ClientHeightThe CLIENT rectangle: the room this control can actually paint in, which is WindowRect minus the frame and any scrollbar the window reserved. A layout that wants to know how much space it has wants THIS one. The two singles are that rectangle's size in DESIGN units, the same units as Left, Top, Width and Height, so they can be compared with the geometry of what was placed in the window; a FORM publishes both as document rows.
DpiThe DPI of the monitor this window is ON, read from the window rather than remembered, so a form moved between two monitors answers differently. 0 before the window exists, which is how a caller tells "not created" from a real reading.
ReferenceDpiThe DPI this form's DESIGN measurements were written against (the system's, i.e. the primary monitor's), as opposed to Dpi, which is the monitor the window is on right now. A script that lays controls out itself in pixels needs both: the gaps and offsets it authored are design units while a control's Width comes back in pixels, so round(design * form.Dpi / form.ReferenceDpi) is the whole conversion, and on the reference monitor it answers the design value unchanged.
Focused, SetFocus([idOrHandle])Whether the control holds the keyboard focus, and the way to take it, which turns the focus cue back on with it. With an argument it focuses a control OF THIS WINDOW, named by an id or a window handle, which is what a form needs to focus something it only has a number for. The pair a script uses instead of fetching a handle and calling into the API.
TabIndexWhere the control sits in its container's TAB ORDER, the VB property: 0 is the first stop. It is an ORDERING VALUE and nothing else, independent of the handle, the id and the Z-order position, and two controls may share one, in which case the tie follows the order they were added. Nothing moves when it is set, and a control starts at the place it was created in.
SetBounds(x, y, width, height)Places and sizes in ONE call, in design units. Left/Top/Width/Height are four properties and each one moves the window on its own, so laying out a form with them pays four window calls for what this pays one.
MoveWindow(x, y, width, height [, repaint])Place and size in PIXELS, which is what a layout computed from a window rectangle needs: SetBounds above is the same job in DESIGN units, and the two do not convert into each other. The last argument repaints the window and defaults to true.
ToTop(), ToBottom()Move the control to the top or the bottom of its siblings' Z-ORDER, without moving, resizing or activating it. A control created LATER sits above an earlier one, which is why a size handle has to be raised as it is positioned, and something drawn behind a control (a ring around a selected one) has to be sent down.
SetFont([name] [, size] [, bold])The font in one call, through the same three properties a script can set one by one, so the two cannot disagree: a name left out keeps the engine's font, a size of 0 the engine's size.
Invalidate()Marks the control for repainting, which is what a script that changes a DRAWING asks for. Nothing is painted here and nothing waits: the engine deliberately avoids the synchronous redraws that flicker.
Theme (on a form)A RichTextBox follows it like every other text surface: its client is its own, so it is given the host's background and ink (a Custom palette first, else the leg's pair) unless the script set a colour itself, and switching back to light hands both back. An MDI frame hands the leg to its DOCUMENT WINDOWS as well, whose own dark flag and colour palette are what colour the controls inside them. A CheckBox and a RadioButton take NO theme sub-app under a dark or Custom host, because a themed toggle paints its own face while it is held down: that face is the theme's button colour, and on a dark panel it read as a grey band across the whole control and its caption. With no sub-app the toggle keeps the host's colour in every state and its feedback is the glyph.
PaintsHow many times this window has been asked to paint. It is the instrument a "it flickers" report needs: a child's WM_PAINT is not forwarded to a script handler, so no script could otherwise count them. Read it around a change to tell a repaint storm from a single repaint (measured on the clipboard runner's Wrap toggle, 3 paints of the rebuilt box before the bracket below existed and 1 after it).
BeginUpdate(), EndUpdate()Freeze this control's painting for a bulk change and repaint ONCE at the end, which is what a fill or a rebuild needs: outside the bracket a bulk write pays a paint per item the pump happens to dispatch, inside it pays none, and EndUpdate repaints the control and its children exactly once. It works on ANY control, a FORM included, and freezing the form is the shape a panel uses when it replaces one of its children: the band the destroyed child leaves is the form's own background, so the form is what has to be frozen. The pair is a hint rather than a lock, so an unmatched EndUpdate just repaints.
UpdateWindow()Paint it NOW, synchronously, where Invalidate() only marks it dirty. The exception rather than the rule, because a synchronous redraw is the flicker the engine avoids, so reach for it when something has to be on screen before the next statement: reading pixels back, or any measurement of a drawing.
Text, AppendText(text), Hide()The caption or content. AppendText adds to it in place, which is what keeps a log box from flashing where re-assigning Text repaints the lot; Hide() is Visible = false.
TextLengthThe number of characters in the text, in ONE message and without building the string, for a check that runs on every pass. It counts a line break the way Text reads it, so it is NOT the position SelectionStart and Select use: a RichEdit addresses its content with one character per break.
AppendText(text, rgb)Append one run IN ONE COLOUR, which is what a log needs: the call inserts the text and colours exactly the run it added, with the same colour path SetTextColor uses. A control that is not a RichEdit appends the text and ignores the colour, because a plain EDIT has no per-run format.
SelectionStart, SelectionLength, SelectedTextThe selection, in the control's OWN character positions: assigning the start moves the caret and keeps the length, assigning the length keeps the start. A RichEdit counts a line break as ONE character while its Text reads two, so the two numbers are not text offsets. SelectedText is the range itself, which is what a Find feature reports, and ASSIGNING it replaces that range in one message: an empty string deletes it, which is how a companion column trims itself when the text it numbers gets shorter (and it touches nothing outside the range, so no whole-document write and no repaint of the lot).
Select(start, end), SelectAll()Set the range in the same positions SelectionStart reads, or take the whole text. A NEGATIVE position is refused rather than clamped, because LineIndex answers -1 for a line the control has no layout for yet and clamping that to 0 selects the whole document: guard it, or ask LineIndex(LineCount) for the end position, which is in the same unit.
LineCount, LineIndex(n), FirstVisibleLine, ScrollToCaret(), CharPosition(index)The rows of a text control. LineCount counts what a READER sees, so a text that ends with a line break is not given a phantom last row (a RichEdit's own count does that), an empty document is ZERO rows, and a WRAPPED line contributes one row per row it takes, which is the unit LineIndex and CharPosition speak. LineIndex turns a line into a position for Select, and answers -1 for a line past the end or one the control has not laid out yet: that -1 is a real answer to check, never a 0. FirstVisibleLine reads and sets the row at the top, which is how a second window beside a log follows it. ScrollToCaret() works on a read-only control nobody has clicked, where EM_SCROLLCARET alone scrolls nothing. CharPosition answers [x, y] in the control's client area, for lining up a companion window.
CharHeight, LineSpacingThe text's height and the row spacing, in TWIPS (1/1440 inch), which is the unit a RichEdit really uses. LineSpacing above zero states an EXACT row height, the shape that keeps two controls' rows equal whatever a line holds (a line carrying a glyph the ASCII metrics do not cover draws 2 px taller); zero returns to the control's single spacing.
ReadOnlybool. A text control refuses EDITS while still allowing selection, copying and scrolling, because this is the control's own state rather than a style bit. A control with no such notion remembers the value and ignores it, so one flag can be set on a panel without checking what it holds.
HasKeyboardFocusbool: whether the keyboard focus is on this control OR anywhere inside it, which is the question a panel asks before deciding that a copied value came from itself.
TextHeightPxThe height the control's font is DRAWN at, in pixels for the control's own DPI: the number the font was created with. A companion window lining its rows up with the text needs it, and it cannot be reproduced from FontSize alone because the monitor's DPI and the engine's default size are part of the arithmetic.
Left, Top, Width, HeightPosition and size in design pixels, scaled with the DPI. Assigning one re-applies the window bounds.
Visible, Enabledbool. A disabled control's text takes ThemeDisabled on a Custom form.
DockA DockStyle, so it is written with the enum's own names: DockStyle.None, .Left, .Top, .Right, .Bottom or .Fill. The whole number is accepted too (4 is DockStyle.Bottom), but the name is the spelling to prefer. Docking is re-applied by the engine on every resize and after a DPI change, so a docked control stays docked when the window moves between monitors. A Dock assignment REPLACES the position the control was created with, so the coordinates in a Create... call are what an UNDOCKED control gets.
Margin, MarginLeft, MarginTop, MarginRight, MarginBottomThe inset a DOCKED control keeps inside the band the layout gives it, in design pixels and scaled with the DPI like the container's Padding. Margin sets all four sides and a side set on its own WINS, so box.Margin = 4; box.MarginLeft = 20; is 20 on the left and 4 everywhere else; a side set to -1 hands it back to Margin. This is what stands one docked box off an edge without padding the whole container, and an absolutely positioned control ignores it, having been put where it belongs. A negative value is refused by name.
FontName, FontSize, FontBoldThe control's own font. The engine applies it to the window, and a control the engine paints itself selects it for its drawing.
TextColor, BackgroundColorA colour pair, written 0xRRGGBB, that WINS over the form's theme or palette; left unset it follows the form. A Custom form's palette is what a child takes when it sets neither. A RichTextBox takes the background through its own message, so the value reaches its client like any other control's.
SetTextColor(rgb)The colour of the text this control holds RIGHT NOW, written 0xRRGGBB like every other colour: on a RichEdit it colours the CURRENT SELECTION, which is how a log paints the run it just inserted (with nothing selected the whole text takes it), and on any other control it is TextColor. The byte order a control message wants is derived inside, so a script never has to swap red and blue: handing a raw value to EM_SETCHARFORMAT's crTextColor paints a red as violet.
ScrollBarbool, a NARROW bar drawn by the engine instead of the native one: 45% of the metric wide, in the host’s background with a blended thumb, and it drives the control (a track click pages, the wheel moves three lines, the thumb drags, and the pointer is the hand over the thumb and the arrow over the track). The text is kept off it with EM_SETRECT. A multiline EDIT and a RichEdit only, and the window must be created without WS_VSCROLL, which is what the refusal names.
Handle, Parent, Name, TagThe HWND (IntPtr, usable as long), the control it sits in, a script-side name, and a slot for anything a script wants to hang on it.
ClientToScreen(x, y), GetPixel(x, y)A client point as screen coordinates, and a client pixel. A pixel is a COLORREF (0x00BBGGRR), so compare colours through a colour property rather than through one, and a point outside the client answers CLR_INVALID rather than a colour.
ReadStyle([bEx]), HasStyle(name), SetStyle(name, on)The style word as a number, a style FLAG asked by its NAME (HasStyle("WS_BORDER")), and one set by name. bEx selects the extended word. ModStyle, StyleAdd and StyleRemove take bits rather than a name, which is what the block below covers.
Dispose()Releases the control's window. A using block disposes it at the end of its scope, which is the shorter spelling of the same thing.
SetWindowHandler(fn)Sends THIS window's messages to (hwnd, msg, wParam, lParam) => { ... }, whose answer is the result Windows gets. It is the one hook a script has for a message the engine does not name, and a handler forwards what it does not take to DefWindowProc.
DefWindowProc(msg, wParam, lParam)Windows' own handling of a message for this window, which is what a handler answers for the messages it does not take (and what keeps the window valid underneath the handler).
CallWindowProc(previous, msg, wParam, lParam)Sends a message to a window procedure a script already holds, which is how a chain of handlers is kept going.

A docked control's inset is its own Margin, and the number written is the distance it gets. Padding belongs to the WINDOW (it insets every docked edge equally, and is what keeps a docked box's scrollbars off the frame); Margin belongs to the CONTROL, per side, and REPLACES the padding on the sides it names, so one docked box can stand 20 px off the left while the rest of the window keeps its padding. Between two controls the same number is the gap between them. A side set on its own wins over Margin, and -1 hands a side back to it:

// this left edge is at 20, whatever the padding says
logBox.Dock = DockStyle.Fill;
logBox.MarginLeft = 20;

// all four sides; a side set on its own wins, and -1 hands a side back to Margin
logBox.Margin = 4;
logBox.MarginLeft = -1;

// 0 is an answer of its own: flush with the client edge, padding included
logBox.MarginLeft = 0;

A text colour is 0xRRGGBB however it is built, and SetTextColor takes it that way too. On a RichEdit it colours the CURRENT SELECTION, which is what a log needs (it paints the run it has just inserted); with nothing selected the whole text takes it, and on any other control it is the same as TextColor. The one value that must NOT be handed to it is a GetPixel reading: that is a COLORREF, so convert it with Colors.FromPixel first.

// the forms the argument takes: a literal, a named colour, or one composed from its parts
logBox.SetTextColor(0xE05252);              // a red, written as every other colour is
logBox.SetTextColor(Colors.Red);            // the same red by name
logBox.SetTextColor(Colors.RGB(224, 82, 82));   // and composed

// a RichEdit's per-run colour: select the range, then colour it. This is what a log does per entry.
logBox.SendMessage(EM_SETSEL, start, end);
logBox.SetTextColor(0x4FC3F7);                 // the run just selected

// the WHOLE control, through the property (a RichEdit takes it on all of its text)
logBox.TextColor = 0xF0F0F0;

// a colour read off the screen has to be converted first: a pixel is a COLORREF
logBox.SetTextColor(Colors.FromPixel(logBox.GetPixel(4, 4)));

A Fill box with form.Padding = 4 and MarginLeft = 20 starts at x = 20 with its right side still on the padding, and a Bottom bar with MarginBottom = 6 leaves 6 px below it. The value is in design pixels and scales with the DPI like Padding, only the DOCK layout reads it (an absolutely positioned control already sits where it was put), and a negative value is refused by name.

A control is MADE by the form that holds it: form.CreateButton("OK", 8, 8, 80, 24) and the rest of the factories are Form methods, listed under Form.

Window styles and window messages (on every control)

ctrl.ModStyle(add, remove [, bEx])Add add and remove remove in one change, then re-apply the frame.
ctrl.StyleAdd(bits [, bEx])Add one or more WS_* style bits.
ctrl.StyleRemove(bits [, bEx])Remove one or more WS_* style bits.
ctrl.SendMessage(msg, wParam, lParam)Send a window message to the control's own window and return the message's result.
ctrl.PostMessage(msg, wParam, lParam)Queue the message and answer whether it was queued, without waiting for it to be handled.

These are the raw-HWND operations applied to the control's own handle, so a wrapped control needs no .Handle in the call. They exist on every control the factories return (button, text box, check box, status bar, tab, and the form itself), and bEx = true selects the extended style word (GWL_EXSTYLE: WS_EX_*) instead of the plain one (GWL_STYLE: WS_*). Read a word back with ctrl.GetWindowLongPtr(-16) (plain) or -20 (extended), and write one with ctrl.SetWindowLongPtr(-16, word), the pair's two halves:

// a status bar pinned to the bottom of its form, with a raised edge var bar = form.CreateStatusBar(0, 0, 200, 24); bar.StyleAdd(0x00800000); // WS_BORDER bar.StyleAdd(0x00000200, true); // WS_EX_CLIENTEDGE, on the extended word bar.ModStyle(0x00200000, 0x00800000); // add WS_VSCROLL, drop WS_BORDER, in ONE change bar.StyleRemove(0x00000200, true); // take the extended edge back off // the same bar through the configure callback: no variable, and the style work happens where the control is born form.CreateStatusBar(0, 0, 200, 24, (sb) => { sb.StyleAdd(0x00800000); sb.StyleAdd(0x00000200, true); });

The two message members are the same raw-HWND operation applied to the control's own handle, so no .Handle appears in the call. They exist on every control the factories return, and on the form itself. PostMessage answers a boolean, so it reads directly as a condition:

// expand a tree item, then scroll a log box down one line, with no handle in sight tree.SendMessage(0x1102, 2, item); // TVM_EXPAND, TVE_EXPAND var queued = log.PostMessage(0x0115, 0, 0); // WM_VSCROLL, SB_LINEUP, answered true or false

Use the handle-taking spelling for a window nothing wraps: both doors make the same call.

A tooltip on any control

ctrl.SetToolTip(text)Attach the control's tooltip, or change its text if it already has one. Returns the tooltip's window handle.

This is the handle-taking tooltip call applied to the control's own handle, and it is the same tooltip: one per window, created on the first call, re-texted after that rather than given a second tool, and destroyed with the control. A window the engine does not wrap keeps working through the handle-taking spelling, whose tooltip is created once per handle and kept for the process.

// both spellings reach the SAME tooltip for a wrapped control var box = form.CreateTextBox("", 12, 12, 200, 24); var tip = box.SetToolTip("Type the account number here"); box.SetToolTip("Type the account number (8 digits)"); // same window, new text // and the same box created with its tip already on it form.CreateTextBox("", 12, 12, 200, 24, (tb) => { tb.SetToolTip("Type the account number (8 digits)"); });

Events (assign as script functions)

ResizeEvent(Form sender, ResizeEventArgs e) => { ... } called on WM_SIZE: e.Width and e.Height are the new client size.
Command(Form sender, CommandEventArgs e) => { ... } menu commands (WM_COMMAND), where e.Id is the id the item was added with, and WM_NOTIFY notifications, where e.Id is 0x10000 + code. A notification is not a command, and the ones a control sends while it paints arrive here too (a themed control's custom draw is 0x10000 + NM_CUSTOMDRAW, twice per paint), so dispatch on the ids you know. e.Time, and e.UtcDateTime for a date, say WHEN the message arrived: two events with the same time are one delivery seen again, which is what a handler that must act once compares.
Timer(Form sender, TimerEventArgs e) => { ... } WM_TIMER from a Win32 timer armed on the form: e.TimerId is the one that fired.
Closing(Form sender, CancelEventArgs e) => { ... } set e.Cancel = true to prevent close.
Closed(Form sender, CancelEventArgs e) => { ... } after the form has closed.
AcceptDroppedFilesWhether this WINDOW takes a dragged file, and the switch that turns it on: a window that never accepted a drop is sent none, so a DropFiles handler needs this set to be reached at all. It is the window's WS_EX_ACCEPTFILES bit, so a script reads the state back, and turning it off stops the drops. It is on every control and not only on a form, because the drop goes to the window under the cursor: a RichEdit that covers its form takes drops of its own, and so does a button.
DropFiles(Control sender, DropFilesEventArgs e) => { ... } files dropped via WM_DROPFILES, for ANY window whose AcceptDroppedFiles is on: a form, a button, a RichEdit, a GenericControl. Every window needs its own, and that is Win32 rather than this engine: the message goes to the window under the cursor and is never passed up to the parent, so a control that covers its host is the only window that sees the drop. The event answers the FILES (e.FileCount(), e.FileName(i)), and the engine releases the drop list when the handler returns, so a script never allocates a buffer or calls DragFinish. The raw handle is still there as e.HDrop for a caller that needs it. Do not subclass a control to get its drops: SetWindowHandler REPLACES the engine's window proc, and with it the painting, the theme and the colours the control had.
KeyDown(Form sender, KeyEventArgs e) => { ... } WM_KEYDOWN: e.KeyCode is the numeric virtual-key (0x74 is F5, 65 is A), e.KeyValue the same key as a NAME, and e.Alt / e.Control / e.Shift the modifiers held at the key event.
Paint(Form sender, PaintEventArgs e) => { ... } custom GDI painting. The DC is the one the engine already holds (e.Hdc, with the clip rect as e.Left/e.Top/e.Right/e.Bottom), and the drawing members work THROUGH it so nothing fetches a second one: e.Fill(x, y, w, h, color) a solid rectangle, e.Frame(x, y, w, h, color [, lineWidth]) an outline, e.Disc(x, y, w, h, color) a filled ellipse, e.Ellipse(x, y, w, h, color [, lineWidth]) an outline ellipse, e.Line(x1, y1, x2, y2, color [, lineWidth]), e.Text(x, y, text [, color]) at a point and e.Text(text, x, y, w, h, color [, format]) inside a box with DrawText's flags, e.SetTextColor/e.SetBkMode/e.SetBkColor for the colour that follows (GDI keeps it, the way it does for VBA). Each of those makes and deletes what it needs, so a repaint loop leaks nothing; a script that wants a HANDLE of its own calls e.CreateBrush/e.CreatePen, selects it with e.SelectObject (which answers the object it displaced, so it can be put back), draws with e.Stroke/e.StrokeEllipse/e.StrokeLine/e.FillRect (the DC's current pen or brush), and then e.DeleteObject. e.StockObject(5) is the hollow brush and e.StockObject(8) the no-line pen. A THEMED part of this window is drawn the same way: e.ThemePart(windowClass, part, state, x, y, w, h) and e.ThemeText(windowClass, part, state, text, x, y, w, h [, flags]) open and close the theme handle around the one call, so a repaint cannot leak one, and both answer -1 when this machine has no theme for that class.
EraseBackground(object sender, nint hdc) => { ... } return true to prevent default background erase (flicker reduction).
Load(Form sender, EventArgs e) => { ... } once, on the first Show(), after the window is on screen. The window itself exists from Application.CreateForm (hidden), so this is the event that marks "about to be seen", and a handler assigned right after CreateForm still runs: build everything, attach the handlers, then Show(). A form that is never shown never raises it, and showing a form again does not raise it twice.
SetWindowHandler(long hwnd, long msg, long wParam, long lParam) => { ... } EVERY window message, the ones the engine does not name included, and it is a member rather than an event: its answer is what Windows gets back, so a handler returns DefWindowProc(msg, wParam, lParam) for the messages it does not take. This is how a script receives WM_CLIPBOARDUPDATE from AddClipboardFormatListener (the recipe is in the Clipboard entry), a notification from a native library, or a message another process posts to the window.

Child control events

Click, DoubleClick(Control sender, EventArgs e) => { ... }
MouseDown, MouseUp, MouseMove(Control sender, MouseEventArgs e) => { ... }
GotFocus, LostFocus(Control sender, EventArgs e) => { ... }
Event payloads are fixed by the raise site, not by the handler's declared parameter types. Form-level events (Closing, Closed) deliver sender = Form and a real CancelEventArgs instance Closing is the single veto point: e.Cancel = true prevents the close. Control events (Click, DoubleClick, MouseDown, …) deliver sender = the control (e.g. Button) and a plain EventArgs the click already happened, so there is nothing to cancel: e.Cancel fails with "Property 'Cancel' not found on type EventArgs", and e as CancelEventArgs returns null because EventArgs (a struct) and CancelEventArgs (a class) are unrelated types. Declared handler parameter types are decorative: the engine passes the raw payload regardless (named-object coercion is a pass-through), so a handler typed (Form sender, CancelEventArgs e) => { ... } on a button's Click runs silently with (Button, EventArgs) and the mismatch is only visible when you touch e.Cancel. Prefer untyped (sender, e) => { ... } and inspect the real runtime types with typeof(sender) / typeof(e). To veto a close triggered from a button, set e.Cancel = true in the form's Closing handler instead.
Full demo: assets/language/ui/demos/rich_editor.slc
Menu A menu bar or a popup, built by name: the items, the submenus, and the Command event a click arrives as

A menu is built BY NAME rather than by handle, the same division ClassHandlesMouse and the Invalidate family make: the ids and the Win32 flags are the engine's, and the words are the script's. Menu.Create() is a bar for a window, Menu.CreatePopup() a context menu, and a submenu is a popup added to another menu, so the object that owns an item is always the one it was added on. Nothing needs a menu handle: form.SetMenu applies one and Menu.Of reads back what a window wears.

Menu members

Menu.Create(), Menu.CreatePopup()Both return a DISPOSABLE object. An empty MENU, for a window's bar, and an empty POPUP, which is a context menu or a submenu. Each starts with no items, and each owns a Win32 handle that Dispose() destroys, or a using block at the end of its scope.
Add(text, id)Append an item. The id is the number the click will report, which is what a handler compares against; the text is what the user reads, and a & in it marks the accelerator ("&File" underlines the F).
AddSeparator()A divider, which is what a menu wants between groups rather than a blank item. It carries no id and cannot be picked.
AddPopup(text)Add a SUBMENU and ANSWER it, so its items are added on the object that owns them. It appends to whatever menu it is called ON, so a popup holds a submenu as well as a bar does: var recent = file.AddPopup("&Recent"); is a submenu inside a popup, and it nests further (recent.AddPopup("More")). A nested item still reports its own id to the form's Command event, however deep it sits: var file = m.AddPopup("&File"); file.Add("&Open...", 1001);. Any depth works, since a submenu is itself a menu.
Popup(owner), Popup(owner, x, y)Show this menu as a CONTEXT menu: with no point, at the CURSOR, which is what a right-click wants; with x and y, at a point the caller names, which is what a keyboard menu wants. It returns when a pick is made or the menu is dismissed, and a pick arrives through the SAME Command event a bar item uses, so there is one handler for both.
Menu.Of(form)The menu a window is WEARING, or null. It asks the WINDOW rather than remembering, so it agrees with what is really applied, and a form with no menu answers null.
Dispose()Destroy the menu and its items. A using block disposes it at the end of its scope, the shorter spelling of the same thing. Take a bar off its window with form.SetMenu(null) before destroying it.

Where a click arrives, and the one order that matters

An item is picked from either place through the same event, so a script writes one handler. The id the item was added with is read from e.Id, which the engine hands the handler, and the same object says WHEN it arrived: e.Time is the key for acting once, e.UtcDateTime the same moment as a UTC date for a log line.

CommandThe form's event, raised when a menu item is picked. It is the same event a control's notification arrives as, and both are the engine dispatching WM_COMMAND: a control carries its window in the message and a menu item carries nothing but the id, which is the whole difference.
e.Id, e.Time, e.UtcDateTime, e.Hwnde.Hwnd says WHICH window sent it: a CONTROL carries its own handle there, while a MENU item carries 0, because a menu is not a window and its id travels in the message instead. So e.Hwnd == 0 is how a handler tells "a menu item" from "a control" with no extra bookkeeping.

form.SetMenu(menu)Wear a menu as the window's bar; null takes the bar away without destroying the menu. A later SetMenu replaces the bar, and the engine does not destroy the one it replaced, so a script that builds bars in a loop owns what it replaces.

The handle has to exist first. A form has no window until it is shown, so a SetMenu called before Show() applies nothing and Menu.Of answers null; the same is true of a popup's owner. Set the bar after the window exists, which is where a Load handler runs. A pick is delivered by the message loop, so a program that builds a menu and ends never sees one: Application.Run() is what pumps it, which is why the sample below is a whole program rather than a fragment.

// a bar with a submenu, and a context menu on a right-click var form = Application.CreateForm("Menu demo"); form.Width = 480; form.Height = 220; form.Show(); // the window, and so the handle, exists from here var m = Menu.Create(); var file = m.AddPopup("&File"); file.Add("&Open...", 1001); file.AddSeparator(); file.Add("E&xit", 1000); m.Add("&Help", 1099); form.SetMenu(m); // a bar applies to a window that EXISTS, so Show comes first var pop = Menu.CreatePopup(); // a context menu: same items, same event pop.Add("Cut", 2001); pop.Add("Paste", 2002); form.Command = (s, e) => { // a bar item and a popup item both arrive HERE if (e.Id == 1000) form.Close(); // Exit if (e.Id == 1001) form.Text = "opened"; // Open if (e.Id >= 2001) form.MessageBox("popup item " + e.Id, "Menu", 0); // Cut or Paste, by its id }; form.MouseDown = (s, e) => { // the popup opens where the user points if (e.Button == MouseButtons.Right) pop.Popup(form, e.X, e.Y); // the NAME: MouseButtons is a script type here }; Application.Run(); // the loop that DELIVERS Command, returning when the last form closes form.SetMenu(null); // take a bar off before destroying the menu it pointed at m.Dispose(); pop.Dispose();

The event carries four values, and each has a job. e.Id is the id the item was added with. e.Time is the raw tick since boot, which is the key for acting ONCE: two events from one delivery carry the same value and a genuine second click a different one, and comparing two ticks needs no clock. e.UtcDateTime is that same moment as a UTC DateTime (its Kind is Utc), which is what a log line wants. e.Hwnd says WHICH window sent the event: a control carries its own handle there, while a menu item carries 0, because a menu is not a window and its id travels in the message instead. So e.Hwnd == 0 tells a menu pick from a control with no extra state.

A control answers the calls that want an hwnd. The handle-taking spelling stays for a window nothing wraps, and the receiver form is that same call with the plumbing done: form.MessageBox(text [, caption] [, type]), where the handle a script would have fetched and handed back is the one the control already holds. MessageBox is the first of these, and the flags are the same values the namespace takes (1024 is MB_SYSTEMMODAL). It is a member the engine adds ONE at a time, where the receiver can supply what the call needs and no engine name already claims it.

The Win32 namespace described in this chapter is the ESCAPE HATCH, and it is meant to stay that way. It is the way to reach a Windows call the engine does not wrap, and above all an EXTERNAL LIBRARY of your own through LoadLibrary and GetFunction, which is nobody else's business to wrap: var k = LoadLibrary("kernel32"); k.Sleep(50); k.FreeLibrary(); The library ANSWERS ITS EXPORTS by name, so no separate lookup call is needed to reach one: k.Sleep(50) is the call, and k.FreeLibrary() is a member of the library object rather than an export. LoadLibrary is a GLOBAL rather than a namespace member: it is the spelling, and the object it answers carries the exports. A call that is part of the engine's OWN model gets a receiver form instead, because the control already holds the handle and the call reads better without it. The two are not competitors: the namespace stays complete for what a script must reach on its own, and the doors grow where the model wants them.

A menu is IDisposable, so using scopes it. The teardown in the sample above is written out because the window outlives it; when a menu's whole life fits in one block, the shorter spelling is the language's own, and the scope disposes it on the way out:

using (var m = Menu.Create()) { m.Add("&About", 1099); form.SetMenu(m); form.SetMenu(null); // take the bar off first: a destroyed menu must not stay on a window } // and the scope disposes it here
Control props Design-time control metadata (typed property table)

Designer support used by the RAD form designer: each control's editable properties and its style flags as NAMED rows rather than positional arrays. PropList() answers ControlProp objects (Name, Type, Value) and StyleFlags() answers StyleFlag objects (Name, Bits, Extended, Field, Offered). Both are script types, so typeof(row) names one a script can write back. The table is compiled per kind, so a row costs no runtime reflection of its own.

ctrl.PropList()The control's editable properties, one ControlProp row each (a script type with Name, Type and Value). It IS the design table itself, so a designer and a script read the same one.
ctrl.GetProp(name)Current value of that property, from the same table; a name this kind does not carry throws.
ctrl.SetProp(name, value)Applies the value and returns 1, through the same validation the designer uses; an unsupported name throws. Writing the value the control ALREADY holds is a no-op rather than a write, because several of these setters do more than store (a FontSize re-applies a font) and a document that merely restates a property must not perturb the control it describes.
Style, ExStyleThe two WINDOW-STYLE WORDS, and they are rows like any other, so a saved document carries a control's style. A style is a bit field, so one row per flag would be the alternative: the WORD is what a document needs, and turning a flag into a bit is StyleFlags() and SetStyle.
ClientWidth, ClientHeightA FORM's client area in DESIGN units, the room its children were placed in. The rows exist so a document says the space its layout was designed against and a reader can check it; they are the one pair a row applier never writes, because a client area is what the frame left rather than a request.
ctrl.NameThe name its creator gave it: the designer entry name, or what a script assigned. A handler reads it to tell WHICH control it was handed. Empty until something sets it, and it is a row of the table above too, so GetProp("Name") answers the same thing.
These are the only spellings: the UiDesign and UiStyle namespaces that carried them are gone.
// the control is the door, and the table it reads is the designer's var rows = btn.PropList(); foreach (var row in rows) { print(row.Name + " (" + row.Type + ") = " + row.Value); } print(btn.GetProp("Text")); btn.SetProp("Left", 40); btn.SetProp("BackColor", 0x202020); // the same table whether the control is held as a typed Control or as a plain object

A handler is given the control that raised the event, and can inspect what it was given: s.Name is the name above, s.GetType() answers the control's own type (Button, TextBox, a Form for a form's own events) and that type's own properties read on it, so s.GetType().Name is the type name, s.GetType().FullName the full one and s.GetType().BaseType its parent. A type name written directly still means that type's STATIC members (DockStyle.Bottom), which is why the two never collide: statics are tried first.

A whole control serializes as this very table: Json.Serialize(s, true) in a handler answers the rows, one object per property with Name, Type and Value, for every kind including a Form.

An event's arguments serialize as what they carry: a mouse one answers its position AND what the mouse did (X, Y, Button, Clicks, Delta), a key one its key and modifiers (KeyCode, Alt, Control, Shift), and a click's are an empty object, because that event carries no data at all and the sender is the whole story. A key event answers both halves of a key: KeyCode is its numeric code (65, 123, 17) and KeyValue its name ("A", "F12", "Control"), one shape each whatever key it is. A resize answers its name and its size the same way (Event, Width, Height). A key pressed WHILE ALT IS HELD is reported like any other, and Alt reads as down for the whole combination, the Alt key's own release included.

EVERY value answers four reflection verbs, so code can act on members it cannot name at compile time: o.Get("member"), o.Set("member", value), o.Keys() for the names, and o.Call("member", args...). A handler can also tell WHICH event it is in: the sender records it (s.LastEvent) and the arguments carry the same name (e.Event), so one function can serve several events and still know which one it is answering. Keys() lists the names a script would write: a type that keeps backing fields beside its properties reports the properties, and a struct whose members are fields reports those. A Control answers its design table (the rows above, so Get("Text") and GetProp("Text") agree), a script class answers its fields and methods, and anything else answers its public members. A real member of the same name always wins over a verb, and a name the value does not carry refuses with that name.

Property table: every control exposes Name, Text, Left, Top, Width, Height, Visible, Enabled, FontName, FontSize, ForeColor, BackColor; plus Checked (CheckBox, RadioButton), Items (ListBox, ComboBox), and Minimum / Maximum / Value (TrackBar).

A CONTAINER also exposes its CONTENTS, because they are what a saved form cannot do without: Columns (List<ColumnProp>, each with Text and Width) and Items (a List<List<string>>, one entry per row and its cells in column order) on a ListView, Items (List<TreeItemProp>, each with Text and its own Children, so a tree stays a tree) on a TreeView, and Tabs (List<string>) on a TabControl. Each is READ off the control, so the table says what the control holds now, and writing one back goes through the same control members a script uses (InsertColumn, InsertItem, AddTab).

See assets/language/ui/demos/rad_designer.slc for the consumer.

Style flags Style-flag names, bits and the raw word (the design table's sibling)

The NAMES behind a style word. ModStyle, StyleAdd, StyleRemove and the control-side SetStyle / HasStyle / ReadStyle write and read the bits; this table says what the bits are called, so a panel can show what a control has and what it could have instead of a hex word.

ctrl.StyleFlags()Every flag THIS control's kind accepts, as StyleFlag row objects (a script type with Name, Bits, Extended, Field and Offered): the general WS_* / WS_EX_* entries plus that class's own (BS_*, SS_*, ES_*, CBS_*, LBS_*, LVS_*, TVS_*, DTS_*, TBS_*). offered is false for a flag a panel should not show: one that only means something on a top-level window, or one Windows owns.
// the names a panel shows, for the kind of control in hand: var flags = btn.StyleFlags(); foreach (var f in flags) { print(f.Name + " = 0x" + f.Bits); } // the control answers for itself, which is the spelling to prefer: if (btn.HasStyle("WS_BORDER")) { print("bordered"); } btn.SetStyle("WS_VSCROLL", true); print(btn.ReadStyle(false)); // the raw word those flags describe
A flag whose name is a value of a FIELD (a BS_TYPEMASK member, say) is set through SetStyle rather than OR-ed in: setting one value clears its siblings, so BS_CHECKBOX then BS_RADIOBUTTON cannot make 0x7. Offered is false for a flag a panel should not show (one that only means something on a top-level window, or one Windows owns), and Extended says which of the two words the flag lives in. The extended ListView and TreeView families (LVS_EX_*, TVS_EX_*) are deliberately absent: they travel through LVM_SETEXTENDEDLISTVIEWSTYLE / TVM_SETEXTENDEDSTYLE, not through the window's extended style word, so writing them as window styles would set nothing.
ListView A report or detail list: columns, rows, and the two cell rectangles an in-place editor needs

Created via form.CreateListView(x, y, w, h), which gives it full-row select, grid lines and double buffering. It is a SysListView32, so its colours do NOT follow the window theme the way a button's do: they come from SetThemeColors, which is also how a Custom form's palette reaches it.

Methods and properties

InsertColumn(index, text, width)Adds a column at that index and returns its index, or -1. The first column is the one a row's own text goes in.
SetColumnText(index, text)Renames a column's header, which GetColumnText reads back. The header's text is also one of the two things FitColumnsToContent sizes a column to, so a rename widens the column as well.
GetColumnText(index)A column's header text, the read that pairs with SetColumnText. Empty for a column that does not exist, and at most 1023 characters of a longer one, exactly as GetItemText reads a cell.
DeleteColumn(index)Removes a column. The columns to its right keep their order and move one index left, so a row's text then reads from the next column.
InsertItem(index, text)Adds a row at that index whose text lands in the first column, returning the row's index. Appending is InsertItem(lv.ItemCount, text).
SetItemText(row, col, text)Sets one cell's text, col 0 being the row's own text.
GetItemText(row, col)The text of one cell, the read that pairs with SetItemText. An empty string for a cell that does not exist, at most 1023 characters of a longer one, and asking never creates the window.
ItemCountThe rows it currently holds.
Clear()Removes every row; the columns stay.
DeleteItem(index)Removes one row.
SelectedIndexThe selected row, or -1 when none is selected. Assigning selects that row and clears the previous selection.
GetCellClientRect(row, col), GetCellRect(row, col)One cell's rectangle, as a Rect. The first is in the list's OWN client coordinates, for a control parented to the list; the second is in the PARENT form's, for a sibling of the list. Both answer Left and Top of -1 when there is no such cell.
CreateOverlayTextBox(text)An TextBox parented to the list, which is the in-place cell editor: position it with GetCellClientRect and show or hide it as the selection moves.
GetColumnWidth(col), SetColumnWidth(col, width)A column's width in pixels; SetColumnWidth refuses a width below 1.
FitColumnsToContent()Sizes every column to its widest cell plus its header (a floor of 24 px each) and then trims from the right until the total fits the client, so the list does not grow a horizontal scrollbar. Call it after filling the rows, and again after a DPI change.
BeginUpdate(), EndUpdate()Wrap a bulk fill so it costs ONE repaint instead of one per row. The pair lives on every control (see the Control rows), a form included; the note below says why a refill that OVERWRITES beats a clear-then-fill.
SetThemeColors(background, text)The two colours the control draws itself with, written 0xRRGGBB. This is the member a Custom form's palette colours a list view through, because the base colour properties only repaint and never tell a SysListView32 what to draw.
RaiseDoubleClick()Fires the control's DoubleClick handler without a mouse, which is how a test drives a row activation rather than posting a click at a guessed position.
SelectedIndexChangedAssign a handler and it runs when the selected ROW changes, by a click in the list or by an assignment to SelectedIndex. It is raised from the LVN_ITEMCHANGED notification, which is the item-state change rather than a tidied "the selection is now N", so it can arrive more than once for a single move; SelectedIndex is where the answer is read. The notification also reaches form.Command with its code packed into the id, which is the escape hatch for what the engine does not name.
RaiseSelectedIndexChanged()Fires that handler without touching the selection, for a test or a script that has to drive it.

A refill that overwrites is not the same as a clear followed by a fill. The cleared state is one a window can be PAINTED in: a form the engine composes repaints a child in the middle of a fill, and BeginUpdate does not suppress that, so a clear-then-fill list is seen empty for a frame. Read ItemCount, overwrite the rows that already exist, add only the missing ones and DeleteItem the tail:

// created with its two columns already in place, through the configure callback
var lv = form.CreateListView(12, 12, 360, 200, (list) => {
    list.InsertColumn(0, "Name", 140);
    list.InsertColumn(1, "Value", 90);
});

lv.BeginUpdate();
var row = 0;
foreach (var p in pairs) {
    if (row < lv.ItemCount) { lv.SetItemText(row, 0, p.Name); }   // overwrite what is there
    else { lv.InsertItem(lv.ItemCount, p.Name); }
    lv.SetItemText(row, 1, "" + p.Value);
    row = row + 1;
}
while (lv.ItemCount > row) { lv.DeleteItem(lv.ItemCount - 1); }
lv.EndUpdate();
lv.FitColumnsToContent();
InputBox A modal prompt: a title, a line of text and an input, answered or cancelled

Two spellings. Application.InputBox(title, prompt [, defaultValue [, defaultButton [, timeouts]]]) is the one-shot form: it returns what was typed, or null when it was cancelled or closed, so "cancelled" stays distinguishable from "entered nothing". Application.CreateInputBox() gives the OBJECT instead, for a prompt whose size, font, icon, screen or default button a script decides, and ShowDialog() then answers 1 when it was answered and 2 when it was cancelled or closed, with what was typed left in Value.

It is a window the engine assembles from its own Form and controls rather than a Win32 dialog template, which is what lets it take the theme of the window it opened over, and it runs the engine's own message pump while it is up, so a TIMER still fires inside it. The window it was opened from is disabled until it ends, which is what modality means here. Enter answers it, Escape and the close box cancel it, and its window is a message box: a title bar, no minimise or maximise box, a fixed frame.

A message box is the other prompt, and it has TWO doors because the owner is a real choice: ctrl.MessageBox(text [, caption] [, type]) is that control's window as the owner, and the BARE MessageBox(text [, caption] [, type]) is the same call with NO owner, which is what a tool that has no window prompts with. The bare one is a global rather than a namespace member because nobody owns it.

Methods and properties

Title, Prompt, ValueWhat the window is called, the line above the input, and what is typed. Preset Value before ShowDialog() and read it after.
ShowDialog()Runs the prompt: 1 answered, 2 cancelled or closed.
WindowThe prompt's own window while it is up, and 0 the rest of the time.
PostMessage(msg, wParam, lParam), SendMessage(msg, wParam, lParam)The doors Control has, applied to that window, so a script answers the prompt it is inside without a handle in sight.
Width, HeightIts size in design pixels, as a Form's are. A size too small to hold its parts is raised to a minimum rather than opened as a sliver.
Left, Top, StartPositionWhere it opens, numbered as a Form's is: 0 where Left and Top say, 1 centred on the screen, 2 (the default) centred on the window it was opened over.
ScreenWhich monitor it opens on, numbered the Form's way: left alone it mirrors the window the prompt was opened over, and assigning it (before the prompt is up, or while it is) takes it there through the Form's own Screen, which is also what refuses a number with no monitor behind it.
ModalWhether it OWNS the input while it is up, which it does by default: the window that was active is disabled until the prompt is answered, and false leaves it enabled so the application behind the prompt still takes clicks while the prompt waits.
CloseBoxWhether it carries the X at all. Escape cancels it either way.
TimeoutsWhich button answers on its own, and after how long, as a map of the code to milliseconds: { 1: 2000 } is "the OK button after two seconds" and { 2: 2000 } is Cancel. The codes are the ones ShowDialog() already answers with, the EARLIEST deadline wins when both are named, and an empty map means the prompt waits for a hand. This is also the LAST argument of the one-shot spelling, after the default button: Application.InputBox(title, prompt [, defaultValue [, defaultButton [, timeouts]]]).
DefaultButtonWhich button is the default: 0 for OK, which is what it is, and 1 for Cancel, meaning the one Enter activates and the one Windows draws as the default. The input keeps the caret either way, so a script can still type into it.
ThemeThe theme of the window it was opened over unless the script assigns one, so a prompt in a dark or paletted application matches it.
FontName, FontSize, FontBoldWhat the prompt line, the input and the buttons are written in. Left alone they are the engine's own font ONE STEP UP (10 against roughly an 8pt equivalent), so a prompt reads like a message box rather than a dense panel.
TextHeight, TextPadding, TextLeft, TextRightThe INPUT's metrics: its height (56 by default), the space between the prompt line and it (16), and its side insets. The layout is built from them rather than from constants, so a bigger font or a longer line has room instead of clipping, and the buttons keep a height of their own (28), because a tall input is a place to type rather than a reason for fat buttons.
InputThe input control itself while the prompt is up, the same door every control has, so a script can style or fill its own prompt rather than only answer one.
SetIcon(icon [, size [, color]])The prompt's icon, in the Form's own shapes (a character to render, an ICON handle from Application.ExeIcon, or 0 for none). A WINDOW handle is not one: the engine refuses it by name rather than handing it to WM_SETICON, which accepts any handle and would leave the window without an icon in silence. Asked BEFORE the prompt is up it stores the request and returns 0, since there is no window yet to hold an icon, and asked while it is up it applies at once and returns the handle the window holds. A prompt nobody gives an icon to keeps the running executable's own.
Accept()Answer the prompt the way its OK button does, so the caller's ShowDialog() gets the text that is in the box. It posts the same message that button sends, which is what the prompt's own loop reads, so it is handled exactly as a click would be.
Cancel()Dismiss the prompt the way its Cancel button and the Escape key do: ShowDialog() answers 2.
ReadStyle(), WindowRectThe prompt window's own state, read the way a control reads its own: its STYLE word, and the rectangle it BECAME rather than the size requested. Width and Height above are the REQUEST, and a prompt asked for 10x10 opens at the engine's minimum. The InputBox is not a Control, so it carries these as mirrors beside PostMessage and SendMessage, which is also why GetId and the focus members are not on it.

Example

// Rename a button with a prompt: a form, the control it acts on, and the two shapes of InputBox
var form = Application.CreateForm("InputBox demo");
form.Width = 420; form.Height = 160;
var target = form.CreateButton("Button1", 12, 12, 160, 30);
form.Show();

// The one-shot form: the text comes back, and null means it was cancelled
var name = Application.InputBox("Rename", "New name for the control:", target.Text, 0, { 2: 8000 });   // cancels itself if nobody answers
if (name != null) { target.Text = name; }
print("the one-shot answered: " + (name == null ? "null, so it timed out" : name));

// The object form, for a prompt the script decides the shape of
var box = Application.CreateInputBox();
box.Title = "Rename";
box.Prompt = "New name for the control:";
box.Value = target.Text;
box.FontSize = 12;
box.DefaultButton = 1;      // Enter cancels rather than answers
box.Screen = 1;             // the second monitor, so drop this line where there is only one (Application.MonitorCount())
box.Timeouts = { 1: 4000 };   // answers OK itself after four seconds, so this example needs no hand
if (box.ShowDialog() == 1) { target.Text = box.Value; }
print("the object form answered " + target.Text);


// A prompt runs the engine's pump, so a TIMER fires inside it, and the doors answer it
// with no hand on the keyboard: Accept() is the OK button, Cancel() the Escape path
var auto = Application.CreateInputBox();
auto.Title = "Rename"; auto.Prompt = "New name for the control:";
CreateTimer(400, (sender, e) => { auto.Input.Text = "Renamed"; auto.Accept(); }, false);
if (auto.ShowDialog() == 1) { target.Text = auto.Value; }
print("the timer-driven form answered " + target.Text);
Application.Run();   // keep the window up; close it to end the script
DockStyle How a control attaches itself to its parent's edges

What Control.Dock takes, on any control (the form included). The six members are the four edges, Fill for everything the docked neighbours leave, and None for a control placed by hand:

DockStyle.None // 0 positioned by Left/Top/Width/Height DockStyle.Left // 1 DockStyle.Top // 2 DockStyle.Right // 3 DockStyle.Bottom // 4 DockStyle.Fill // 5 takes what the docked neighbours left
var bar = form.CreateStatusBar(0, 0, 200, 24); bar.Dock = DockStyle.Bottom; // pinned to the bottom edge var log = form.CreateTextBox("", 12, 88, 400, 300); log.Dock = DockStyle.Fill; // everything above the bar print(bar.Dock is DockStyle); // True

A whole number is accepted as well (4 is DockStyle.Bottom), which is the general rule for a CLR enum, but the name is the spelling to write: it is also the name typeof(ctrl.Dock) reports, and typename("DockStyle") resolves it. Docking is re-applied by the engine on every resize and after a DPI change, so a docked control stays docked when the window moves to another monitor.

Diagnostics One registry for the engine's run-configuration gates (the diagnostic traces, the two path switches and the frame cap), so a script can read and set any of them while it runs.

The engine's run-configuration gates are readable through Diagnostics rather than only through their environment variables, and there is ONE list of them: the diagnostic traces, the two switches that choose which engine a body runs on (TOPLEVEL_VM and CARRIED_STATEMENTS), the frame cap (VM_MAXFRAMES, a value rather than a flag), and the single-instance lock's name report (SINGLE_INSTANCE). LogTraces(true) turns every trace on and LogTraces(false) takes them all off (the two path switches and the cap are deliberately untouched by it: that switch means the traces), Trace(name, on) sets one gate, and Traces() reports every one with its state, a flag as on/off and the cap as its number. A gate takes effect from the next statement onward, so it is useful in the middle of a run, not only at its start.

AsyncParks() is the one member here that is a COUNTER rather than a gate: it reports how many awaits have WAITED on the spot instead of suspending, in total or for one site (AsyncParks("await foreach")). An await produces the same value either way, so the count is what lets a suite assert that a shape waits, and the async / await entry lists which shapes those are and why each one waits.

Each name is the environment variable's own name without the SLC_ prefix, so Diagnostics.Trace("VM_TRACE", true) and SLC_VM_TRACE=1 are the same gate. The variable is only ever the STARTING value, and ONE rule reads all of them: 1 is on, 0 and false are off, and anything else is the gate's own default. That keeps SLC_TOPLEVEL_VM=false working as the opt-out of a gate whose default is on, and stops a stray value from switching a trace on. An unknown name is refused with the list of real ones rather than ignored.

VM_TRACEThe opcode trace, the same flag as Vm.Trace.A [tr] line per executed unit, with its source position. Use it to see whether a body runs on the VM or is walked.
STACK_TRACEThe live script depth per interpreted call.A [stack:call] and a [stack:unwind] line per call, with the remaining stack, so a recursion's real headroom is visible.
STACK_MAPThe thread's stack regions: commit, guard and reserve.Tens of lines per call, so turn it on alone and briefly. That volume is why Trace(name, on) exists beside the all-switch.
DISABLE_GUARDSBoth recursion guards.Recursion past a cap is no longer refused, so the depth can be measured. Expect a crash rather than an error if it goes too far.
CORO_TRACEThe coroutine walk.Lines for each resume, foreach and yield, which is what a generator that stops early needs.
NAMED_TRACEThe named-argument markers the VM hands to a call.One line per named call, naming the callee and the names it carried. Nothing appears for a positional call.
BAIL_TRACEThe source site that raised a VM bail, a shape the VM hands to the tree walker.One line naming the statement a compiled body stopped part-way at, which is the first question to ask of such a body.
COERCE_TRACEEach CLR-constructor candidate and whether the argument values fit it.The report that explains a choice between same-arity overloads. It has no engine field, so it is read from the variable or through LogTraces, and Trace(name, on) refuses it by name.
TOPLEVEL_VMWhether each top-level statement runs on the VM or the tree-walker.The same state VmSetTopLevelEnabled reads and sets, on by default. See that entry for what changing it means.
CARRIED_STATEMENTSWhether the compiler may hand a top-level statement it cannot model to the tree.The same state VmSetStatementCarrier reads and sets, on by default: SLC_CARRIED_STATEMENTS=0 is the opt-out. It governs a COMPILE, not the engine a statement runs on.
VM_MAXFRAMESThe VM's frame cap, a value rather than a flag.Reported as its number, and settable as one: Trace("VM_MAXFRAMES", 50) moves BOTH caps the variable moves, and 0 restores the platform default. The variable fixes it before the first statement.
SINGLE_INSTANCEWhether the single-instance refusal names the lock it lost.One line, and only when a second run of the same script is refused: the lock's name is a sanitized full path, which is why it is opt-in and the default message is one short line.
ASYNC_TRACEEvery await that WAITS on the spot instead of suspending.One line per wait with its site (await, await foreach, await using, http stream, Task.Wait) and its duration. AsyncParks(site) answers the same question as a number, which is what a suite asserts on, and the async / await entry lists which shapes wait.

Every diagnostic the engine prints carries a position. A warning from a builtin, or the end-of-run COM report, prints the same [Lx:Cy] prefix a refusal does, so a warning can be located without a search: when the caller has no position of its own the engine supplies the statement being executed, which is the case for a builtin (a native is handed values, never a node) and for the report raised after the last statement. A diagnostic from a script run through RunScript is attributed to the CALL instead, because the nested text is not in the file you are reading: see RunScript.

Script: Diagnostics.LogTraces(true); turns everything on for a run that is already going, and Diagnostics.Trace("STACK_TRACE", false); quietens the one that is too loud.

ThemeMode How a window gets its look, including a palette you set yourself

What Form.Theme and MdiForm.Theme take. Light and Dark are the two native looks, System follows Windows' own app-mode setting, and Custom paints the palette you set on the window:

ThemeMode.Light // 0 the light native look ThemeMode.Dark // 1 the dark native look ThemeMode.System // 2 follows Windows' app-mode setting ThemeMode.Custom // 3 paints the palette below
var form = Application.CreateForm("Palette"); form.Theme = ThemeMode.Custom; // the window and the controls inside it form.ThemeBackground = 0x1E1E32; // what the engine paints form.ThemeText = 0xF0F0F0; form.ThemeDisabled = 0x808080; // text of a disabled control var ok = form.CreateButton("OK", 12, 12, 90, 26); ok.BackgroundColor = 0x2E7D32; // a control's OWN colour wins ok.TextColor = 0xFFFFFF; var cancel = form.CreateButton("Cancel", 112, 12, 90, 26); cancel.BackgroundColor = 0xB00020; // each control takes its own pair cancel.TextColor = 0xFFE0E0; print(form.Theme is ThemeMode); // True

A colour the palette leaves unset comes from the effective leg, so setting only the background is enough. That leg is derived from the palette background's BRIGHTNESS, which is what the parts the engine does not paint (a scrollbar, a themed button face) follow, so a dark palette does not sit beside a light scrollbar. Reading Theme answers the mode that was asked for, which is how a script asks "did I choose Custom" (form.Theme == ThemeMode.Custom), while an internal DarkMode answers the leg in force.

The window's TITLE BAR follows the palette too, where Windows allows it: on Windows 11 and later the caption is painted from ThemeBackground with its text in ThemeText, and it returns to the system's own caption as soon as Theme leaves Custom. On an older Windows the caption keeps the system's dark or light one, so a Custom window shows the palette everywhere but its title bar.

Every colour here is written 0xRRGGBB, red in the high byte, as everywhere else in the engine, and a palette member reads back exactly what it was set to. A GetPixel reading of a painted pixel reports the bytes the other way round (0x00BBGGRR, the order a COLORREF carries), so compare colours through the property rather than through a pixel: a red background reads back as 0xFF0000 from the property and as 255 from the pixel.

Colors The colours by name, plus the byte order a colour is written in and the swap a pixel reading needs

The named colours (Colors.Red, Colors.BlueViolet, and the nineteen beside them) are 0xRRGGBB like everything else, so Colors.Red is 0xFF0000 and assigning one paints the colour it names.

Every colour a script writes is 0xRRGGBB, red in the high byte, and every colour member takes and reports it that way. A GetPixel reading is the one exception: it answers a pixel as 0x00BBGGRR, the order a COLORREF carries, so a pixel is not comparable to a colour without a swap. Measured on a red background: the property reads back 0xFF0000 while the pixel reads 255.

FromArgb([a,] r, g, b)Composes a colour the same way, with an optional alpha first: Colors.FromArgb(255, 128, 0) is the orange 0xFF8000, and Colors.FromArgb(128, 255, 128, 0) carries the alpha in the high byte.
RGB(r, g, b)Composes a colour from its three components, each 0 to 255, so Colors.RGB(0xAA, 0xBB, 0xCC) is 0xAABBCC. A component outside that range, or a value that is not a whole number, is refused by name.
BGR(colour)The value a GetPixel reading reports for that colour, so a pixel can be compared with pixel == Colors.BGR(0xFF0000).
FromPixel(pixel)The colour a pixel reading stands for, so a colour can be READ BACK out of a window: Colors.FromPixel(form.GetPixel(x, y)).
var form = Application.CreateForm("Color"); form.Theme = ThemeMode.Custom; form.ThemeBackground = Colors.RGB(0x1E, 0x1E, 0x32); // the same as 0x1E1E32 // the client is painted 0x1E1E32, and the pixel reports it the other way round: print(form.GetPixel(200, 120) == Color.BGR(0x1E1E32)); // True print(Colors.FromPixel(form.GetPixel(200, 120)) == 0x1E1E32); // True print(Colors.RGB(0xC0, 0x20, 0x20)); // 12591136, a colour to set

BGR and FromPixel are the same swap in opposite directions, which is why swapping twice returns the original: one names the colour you are looking for, the other the pixel you read. Greys need neither, since a swap leaves them unchanged.

MdiForm MDI frame container with MDIClient area for document windows

Created via Application.CreateMdiForm(title). Provides an MDI frame with an MDIClient area where MdiChild document windows live. Frame-level controls are positioned above the client area.

Properties

HandleNative window handle (IntPtr).
TextWindow title.
Width / HeightFrame dimensions.
Left / TopScreen position.
ThemeA ThemeMode, so it is written form.Theme = ThemeMode.Dark: Light or Dark, System to follow Windows' own app-mode setting, or Custom to paint a palette. Reading DarkMode answers the effective leg, exactly as on a Form, whose caption follows the palette the same way.
VisibleWhether the window is visible.

Frame control factory methods (all 17 types)

CreateLabel(text, x, y, w, h)Label on the frame.
CreateButton(text, x, y, w, h)Button on the frame.
CreateTextBox(text, x, y, w, h), CreateRichTextBox(text, x, y, w, h)TextBox, or the per-run formatting RichTextBox, on the frame.
CreateCheckBox(text, x, y, w, h, checked?)CheckBox on the frame.
CreateRadioButton(text, x, y, w, h, checked?)RadioButton on the frame.
CreateListBox(x, y, w, h)ListBox on the frame.
CreateComboBox(x, y, w, h)ComboBox on the frame.
CreateListView(x, y, w, h)ListView on the frame.
CreateTreeView(x, y, w, h)TreeView on the frame.
CreateDateTimePicker(x, y, w, h)DateTimePicker on the frame.
CreateTrackBar(x, y, w, h)TrackBar on the frame.

MDI management

>
CreateMdiChild(title [, x, y, w, h, position])Create an MDI child. position: 0=cascade (default), 1=tile, 2=maximized.
TileChildren(horizontal)Tile children horizontally (true) or vertically (false).
CascadeChildren()Cascade all MDI children.
ArrangeIcons()Arrange minimized child icons.
SendMessage(msg, wParam, lParam)Send a window message to the FRAME's own window and answer its result. The same member a Control answers, over the same core, so a frame is driven the way a form is.
PostMessage(msg, wParam, lParam)Queue the message instead of sending it, answering whether it was queued.
MoveWindow(x, y, w, h [, repaint])Place the frame in PIXELS, exactly as Control.MoveWindow does.
GetActiveChild()Returns handle of the active MDI child (IntPtr).
InitHandle()Create window handle without showing.
Show()Show the MDI frame.
Close()Close the frame (triggers Closing/Closed events).

Events

LoadFires when the form loads.
ClosingFires before close (can cancel via ce.Cancel = true).
ClosedFires after close.
ResizeEventFires on resize, receives Size(w, h).
var form = Application.CreateMdiForm("My App"); form.Width = 900; form.Height = 600; form.Theme = ThemeMode.Dark; var btn = form.CreateButton("New Doc", 10, 10, 100, 30); btn.Click = fun(s, e) { var doc = form.CreateMdiChild("Document"); doc.CreateLabel("Name:", 20, 20, 60, 25); }; form.Show(); Application.Run(form);
ChildMdiForm Embedded MDI frame an MdiForm parented to another Form

Created via Application.CreateChildMdiForm(title, parentForm). Same as MdiForm but embedded as a child window of another Form. Useful when you want a regular Form to host the MDI workspace (toolbar at the top, MDI children below), rather than using a standalone top-level MDI frame.

Example

var main = Application.CreateForm("Main Window"); main.Width = 1000; main.Height = 700; main.CreateLabel("File Manager with embedded MDI workspace", 20, 20, 300, 30); var mdi = Application.CreateChildMdiForm("Workspace", main); mdi.Left = 10; mdi.Top = 60; mdi.Width = 980; mdi.Height = 600; mdi.Theme = ThemeMode.Dark; var doc = mdi.CreateMdiChild("Doc 1"); doc.CreateLabel("Content:", 20, 20, 60, 25); main.Show(); Application.Run(main);

Notes:

  • The embedded MdiForm inherits its dimensions and position from the parent Form you must set Left, Top, Width, Height explicitly.
  • All control factories, events, and dark mode work identically to a standalone MdiForm.
  • The parent Form's Closing/Closed events should clean up the embedded MdiForm's documents before the parent window is destroyed.
MdiChild MDI document window created inside an MdiForm

Created via mdiForm.CreateMdiChild(title, x, y, w, h, positionMode). Each child has its own control collection for document-specific controls. Supports dark mode, DPI scaling, and close via Dispose().

Properties

HandleNative window handle (IntPtr).
TextDocument title (appears in title bar).

Control factory methods (same as Form)

>
CreateLabel(text, x, y, w, h)Label on this document.
CreateButton(text, x, y, w, h)Button supports .Click event.
CreateTextBox(text, x, y, w, h), CreateRichTextBox(text, x, y, w, h)TextBox, or the per-run formatting RichTextBox, as a single or multi-line text input.
CreateCheckBox(text, x, y, w, h, checked?)CheckBox togglable boolean.
CreateRadioButton(text, x, y, w, h, checked?)RadioButton mutually exclusive.
CreateListBox(x, y, w, h)ListBox item selection.
CreateComboBox(x, y, w, h)ComboBox dropdown selection.
CreateListView(x, y, w, h)ListView columns, icons, details.
CreateTreeView(x, y, w, h)TreeView hierarchical.
Show()Show the frame this window belongs to, since a document window is shown by its frame. For a document whose root is a single MdiChild that is the frame the reader made to own it.
SendMessage(msg, wParam, lParam)Send a window message to this document window. WM_CLOSE closes it, which is what fires Closing and then Closed.
PostMessage(msg, wParam, lParam)Queue the message instead of sending it, answering whether it was queued.
MoveWindow(x, y, w, h [, repaint])Place the window in PIXELS, exactly as Control.MoveWindow does.
CreateDateTimePicker(x, y, w, h)DateTimePicker date/time selection.
CreateTrackBar(x, y, w, h)TrackBar slider control.

Methods

Dispose()Close and destroy the document window.

Events

LoadFires when the MDI child is created.
ClosingFires before close (can cancel via ce.Cancel = true).
ClosedFires after the document is closed.
ResizeEventFires when the child window is resized. Receives Size(width, height).
var doc = form.CreateMdiChild("Invoice"); doc.CreateLabel("Customer:", 20, 20, 70, 25); doc.CreateTextBox("Acme Corp", 100, 20, 200, 25); var saveBtn = doc.CreateButton("Save", 100, 60, 80, 25); saveBtn.Click = fun(s, e) { print("Saved!"); }; doc.Closing = fun(s, ce) { print("Closing " + doc.Text); }; doc.Closed = fun(s) { print("Closed"); };
ShowConsole Show or hide the console window
ShowConsole(true); // show console ShowConsole(false); // hide console (GUI mode)

▼ LINQ Methods

Where Filter a sequence based on a predicate
Any Iterable works: every LINQ method accepts any Iterable arrays, lists, tuples, dicts (enumerated as KeyValuePairs), HashSets, LINQ results, generators, and strings. Tuples, generators, and dicts materialize on demand when a method enumerates them; a non-iterable receiver (42.Select(...)) is a runtime error.
Where(collection, predicate)
print(Count(Where([1,2,3,4,5], fun(x)=>x > 3))); // 2
Select Project each element using a selector function
Select(collection, selector)
print(Select([1,2,3], fun(x)=>x*10)); // [10,20,30]
SelectMany Project each element to a sequence and flatten

Projects each element into a sub-sequence, then flattens all results.

SelectMany(collection, selector)
print(Count(SelectMany(["hi","ok"], fun(w)=>w.ToCharArray()))); // 4
First Return the first element in a sequence
First(collection [, predicate])
print(First([10,20,30])); // 10 print(First([10,20,30], fun(x)=>x > 15)); // 20
FirstOrDefault Return first element or default value

Returns the first matching element, or default if none found.

FirstOrDefault(collection [, predicate])
print(FirstOrDefault([5,10,15], fun(x) => x > 8)); // 10
Count Count elements in a collection
Count(collection)
print(Count([1,2,3,4,5])); // 5
OrderBy Sort elements in ascending order
OrderBy(collection, keyFn)
OrderBy(collection, keyFn, compareKeys)
print(ElementAt(OrderBy([3,1,2], fun(x)=>x), 0)); // 1
An ordered SEQUENCE, lazily sorted like C#'s: foreach, Count and First() read it, ThenBy adds a second key, and .ToList() / .ToArray() materialize it. The two-argument form takes a comparer that receives two KEYS, so a projection can be ordered by its own rule: people.OrderBy((p) => p.Name, (a, b) => { return b.CompareTo(a); }).
OrderByDescending Sort elements in descending order

Sorts in descending order based on a key selector.

OrderByDescending(collection, keyFn)
OrderByDescending(collection, keyFn, compareKeys)
print(ElementAt(OrderByDescending([3,1,4], fun(x)=>x), 0)); // 4
ThenBy Secondary sort (ascending) after OrderBy

Applies a secondary ascending sort within an ordered sequence.

ThenBy(orderedSeq, keyFn)
var sorted = OrderBy([3,1,2], fun(x)=>x); sorted = ThenBy(sorted, fun(x)=>x);
GroupBy Group elements by a key
GroupBy(collection, keyFn)
var groups = GroupBy([1,2,3,4], fun(x)=>x % 2); foreach (var g in groups) { print(g.Key); }
Aggregate Accumulate values using a function

Applies an accumulator function over a sequence.

Aggregate(collection, func)
var sum = Aggregate([1,2,3,4], fun(a,b) => a+b); print(sum); // 10
All Check if every element satisfies a predicate

Returns true if every element passes the predicate.

All(collection, predicate)
print(All([1,2,3], fun(x) => x > 0)); // true
Any Check if any element satisfies a predicate

Returns true if at least one element passes the predicate.

Any(collection [, predicate])
print(Any([1,2,3], fun(x) => x > 2)); // true
Average Compute the average of numeric elements

Returns the arithmetic mean as double.

Average(collection)
print(Average([10,20,30])); // 20.0
Contains Check if a sequence contains a value

Returns true if the value exists in the collection.

Contains(collection, value)
print(Contains(["apple","banana"], "banana")); // true
Distinct Return distinct elements from a sequence

Filters out duplicates, keeping only unique elements.

Distinct(collection)
print(Count(Distinct([1,2,2,3]))); // 3
ElementAt Return element at index
ElementAt(collection, index)
print(ElementAt(["a","b","c"], 1)); // b
ElementAtOrDefault Return element at index or default value

Returns the element at index, or default if out of range.

ElementAtOrDefault(collection, index)
print(ElementAtOrDefault(["A","B"], 1)); // B
GroupJoin Group joined collections
GroupJoin(outer, inner, outerKeyFn, innerKeyFn, resultFn)
print(Count(GroupJoin([{id:1}], [{oid:1}], fun(o)=>o.id, fun(i)=>i.oid, fun(o,g)=>o.id))); // 1
Join Inner join two collections on key

Correlates elements of two sequences based on matching keys.

Join(outer, inner, outerKeyFn, innerKeyFn, resultFn)
print(Count(Join([{id:1}], [{oid:1}], fun(o)=>o.id, fun(i)=>i.oid, fun(o,i)=>""))); // 1
Last Return the last element in a sequence

Returns the last element, optionally matching a predicate.

Last(collection [, predicate])
print(Last([1,2,3,4,5], fun(x) => x < 4)); // 3
LastOrDefault Return last element or default

Returns the last matching element, or default if none found.

LastOrDefault(collection [, predicate])
print(LastOrDefault([1,2,3], fun(x) => x > 1)); // 3
LeftJoin Left outer join two collections
LeftJoin(outer, inner, outerKeyFn, innerKeyFn, resultFn)
print(Count(LeftJoin([{id:1}], [{oid:1}], fun(o)=>o.id, fun(i)=>i.oid, fun(o,i)=>o.id))); // 1
Max Return the maximum value

Returns the largest numeric value in the collection.

Max(collection)
print(Max([85,92,78,95])); // 95
Min Return the minimum value

Returns the smallest numeric value in the collection.

Min(collection)
print(Min([72,68,85,70])); // 68
Reverse Reverse the order of elements

Returns elements in reverse order.

Reverse(collection)
print(ElementAt(Reverse([1,2,3]), 0)); // 3
RightJoin Right outer join two collections

Joins outer and inner collections, including inner elements even when no outer match.

RightJoin(outer, inner, outerKeyFn, innerKeyFn, resultFn)
print(Count(RightJoin([{id:1}], [{oid:1}], fun(o)=>o.id, fun(i)=>i.oid, fun(o,i)=>""))); // 1
Sum Compute the sum of numeric elements

Adds up all numeric values in the collection.

Sum(collection)
print(Sum([100,200,150])); // 450
Take Take the first N elements

Returns the first N elements from the sequence.

Take(collection, count)
print(Count(Take([1,2,3,4,5], 3))); // 3
Zip Combine two sequences element-wise

Pairs elements at the same position; stops at the shorter sequence.

Zip(first, second)
foreach (var p in Zip(["a","b"], [1,2])) { print(p); }

▼ Bitwise Functions

ToHex Convert number to hex string
ToHex(number)
print(ToHex(255)); // Result: FF
ToHexWithPrefix Convert to hex with 0x prefix
ToHexWithPrefix(number)
print(ToHexWithPrefix(255)); // Result: 0xFF
ToBinary Convert number to binary string
ToBinary(number)
print(ToBinary(42)); // Result: 101010
ToBinaryWithBits Convert to binary with bit separators
ToBinaryWithBits(number)
BitCount Count set bits (popcount)
BitCount(number)
print(BitCount(255)); // Result: 8
IsPowerOfTwo Check if value is a power of two
IsPowerOfTwo(number)
BitSet Set a bit at position
BitSet(number, position)
BitClear Clear a bit at position
BitClear(number, position)
BitToggle Toggle a bit at position
BitToggle(number, position)
BitTest Test if a bit is set
BitTest(number, position)
RotateLeft Rotate bits left
RotateLeft(number, count)
RotateRight Rotate bits right
RotateRight(number, count)
SwapBytes Reverse byte order (endian swap)
SwapBytes(number)

▼ Namespaces & Utilities

WeakRef Script-accessible weak reference holds a reference without preventing garbage collection

WeakRef wraps System.WeakReference<object> and allows scripts to hold a reference to an object without preventing that object from being garbage-collected. This is useful for caches, observer lists, or any scenario where you want to reference objects but allow them to be freed when no other strong references exist.

WeakRef.Create(object)

Creates a new WeakRef wrapping the given object. The object is not strongly rooted it may be collected by GC if no other strong references exist.

var wr = WeakRef.Create(myObj);

WeakRef.TryGetTarget()

Returns the wrapped object if it is still alive (not yet collected), or null if it has been garbage-collected.

var target = wr.TryGetTarget(); if (target != null) { /* use it */ }

WeakRef.IsAlive

Returns true if the wrapped object is still alive (not yet collected) without retrieving it.

if (wr.IsAlive) { /* still alive */ }
// Class with WeakRef tracking non-durable Dispose guard public class DisposableRegistry { public bool[] done; public int disposed; private Dictionary<string, WeakRef> store; public DisposableRegistry(bool[] doneFlag) { store = new Dictionary<string, WeakRef>(); done = doneFlag; } public string Track(string id) { store[id] = WeakRef.Create(this); return id; } ~DisposableRegistry() { if (this.disposed > 0) { return; } this.disposed = this.disposed + 1; store.Clear(); done[0] = true; } } var disposedFlag = [false]; using (var dr = new DisposableRegistry(disposedFlag)) { dr.Track("a"); dr.Dispose(); // explicit Dispose destructor guard prevents re-entry } print(disposedFlag[0]); // true destructor ran exactly once
Lifecycle behavior: The WeakRef itself must remain alive for you to query the target. Once the WeakRef goes out of scope and is collected, the reference is lost permanently. For GC testing in AOT, note that native compilation may keep objects alive longer due to stack roots IsAlive may return true even after null assignment and a full GC.Collect().
Native calls Win32 API interop memory, windows, controls, DLLs

Load a native library and call into it by name. The controls, the memory and the window messages have their own homes now (the form factories, the Mem namespace and the events), so what is left here is the native-call surface itself: LoadLibrary and FreeLibrary, CallFunc, and the errors they raise. All methods are in this namespace.

DLL / module

GetModuleHandle(name)Get a module handle (HINSTANCE) by name, or 0 for the calling process.
GetStockObject(index)Return a handle to a stock GDI object (e.g., DEFAULT_GUI_FONT=17).

Dynamic function calls

CallFunc(lib, name, args...)Resolve a function by name from a loaded library and call it with the given arguments. Supports IntPtr (HWND) handles, int, long, short, byte, uint, strings (UTF-8 call the …A entry points), and any convertible type. At most 16 arguments; pass exactly what the native function expects.
// Get text length from any HWND var user32 = LoadLibrary("user32"); var len = CallFunc(user32, "GetWindowTextLengthW", chatLog.Handle); print("Text length: " + len); // Beep kernel32 var kernel32 = LoadLibrary("kernel32"); CallFunc(kernel32, "Beep", 800, 200); // IsWindowVisible check if a window is visible var visible = CallFunc(user32, "IsWindowVisible", textBox.Handle); print(visible == 1 ? "visible" : "hidden");
CallFunc goes through the same native-call step as everything else (NativeCall, with AotInvoker.InvokeCdeclPtr underneath for AOT-compatible dispatch), so it cannot disagree with lib.Invoke(…) or CallNative about the bytes it sends: strings are marshaled as UTF-8 and freed after the call, IntPtr/UIntPtr handles and numerics pass straight through. The result is the machine value as a long an int-returning export is not sign-extended, so -1 arrives as 4294967295.

Array arguments

Instead of passing individual arguments, pass a single array literal as the third argument. Its elements will be spread as individual native arguments:

// Individual args CallFunc(k32, "Beep", 800, 200); // Same call using array spread var args = [800, 200]; CallFunc(k32, "Beep", args);

SizeOfStruct

Mem.SizeOfStruct("StructName") returns the unmanaged size (in bytes) of a named Win32 structure type. This is useful when allocating memory or calling Win32 functions that require the size of a struct (e.g., RegisterClassExW, GetWindowRect, SendMessage with cbSize fields).

var size = Mem.SizeOfStruct("RECT"); print(size); // 16 (4 fields × 4 bytes each)
// Retrieve the window rectangle using ReadStruct + CallFunc (cleaner) var user32 = LoadLibrary("user32"); var rectSize = Mem.SizeOfStruct("RECT"); var buf = Mem.Alloc(rectSize); var ok = CallFunc(user32, "GetWindowRect", form.Handle, buf); var rect = Mem.ReadStruct(buf, "RECT"); print($"Rect: {rect.left},{rect.top} - {rect.right},{rect.bottom}"); Mem.Free(buf); FreeLibrary(user32);
// Or write fields to a struct buffer: var buf2 = Mem.Alloc(Mem.SizeOfStruct("POINT")); var pt = Mem.ReadStruct(buf2, "POINT"); print($"Point: {pt.x},{pt.y}"); Mem.Free(buf2);

ReadStruct / WriteStruct

Mem.ReadStruct(ptr, structName, fieldName) reads a named field from a struct at the given memory address. Mem.WriteStruct(ptr, structName, fieldName, value) writes a value to a named field. Both use the struct layout from SizeOfStruct to compute field offsets.

Script-defined structs are also fully supported. Mem.ReadStruct(ptr, "MyStruct") returns a struct instance with all public/internal fields populated from raw memory. Mem.ReadStruct(ptr, "MyStruct", "fieldName") reads a single field, and Mem.WriteStruct(ptr, "MyStruct", "fieldName", value) writes a single field. Mem.SizeOfStruct("MyStruct") computes the layout from field types with 4-byte alignment packing.

// Script-defined struct only public fields are included public struct MyPoint { public int x; public int y; } // SizeOfStruct computes 8 bytes (4+4, 4-byte aligned) var s = Mem.SizeOfStruct("MyPoint"); // 8 // Allocate and call GetWindowRect into a script-defined buffer var buf = Mem.Alloc(s); var ok = CallFunc(user32, "GetWindowRect", form.Handle, buf); // ReadStruct returns a struct instance with named fields var pt = Mem.ReadStruct(buf, "MyPoint"); print($"Point: {pt.x},{pt.y}"); // Read/write individual fields var val = Mem.ReadStruct(buf, "MyPoint", "x"); Mem.WriteStruct(buf, "MyPoint", "x", 42); Mem.Free(buf);

The following field names are supported for each struct type:

StructFieldsNotes
WNDCLASSEX / WNDCLASSEXWcbSize, style, lpfnWndProc, cbClsExtra, cbWndExtra, hInstance, hIcon, hCursor, hbrBackground, lpszMenuName, lpszClassName, hIconSm80 bytes (x64)
MSGhwnd, message, wParam, lParam, time, pt48 bytes (x64)
RECTleft, top, right, bottomEach field is int (4 bytes)
POINTx, yEach field is int (4 bytes)
MONITORINFOSee Win32 docsMonitor information (rcMonitor, rcWork, dwFlags)
MINMAXINFOSee Win32 docsWindow min/max tracking info
TCITEMWSee Win32 docsTab control item
LVCOLUMNWSee Win32 docsList-view column
LVITEMWSee Win32 docsList-view item
TVINSERTSTRUCTWSee Win32 docsTree-view insert structure
TVITEMWSee Win32 docsTree-view item
TVITEMEXWSee Win32 docsExtended tree-view item
PAINTSTRUCTSee Win32 docsWM_PAINT paint structure
var buf = Mem.Alloc(Mem.SizeOfStruct("RECT")); Mem.WriteStruct(buf, "RECT", "left", 10); Mem.WriteStruct(buf, "RECT", "top", 20); var l = Mem.ReadStruct(buf, "RECT", "left"); print(l); // 10 Mem.Free(buf);

Exception cases

CallFunc throws clear ScriptException with descriptive messages for these error conditions:

ConditionError message (example)
Invalid library handle (null)CallFunc: invalid library handle (zero). Pass a DynamicLibrary from LoadLibrary or a numeric module handle. Got: null
Invalid library type (script class instance)CallFunc: invalid library handle (InvalidCastException). Pass a DynamicLibrary from LoadLibrary or a numeric module handle. Got: ClassInstance
Function not found in DLLCallFunc: function 'NonExistentFunction' not found in the specified library.
Missing function nameCallFunc: function name required (arg[1])
Missing library argCallFunc requires library and function name.
Too many args (>16)CallFunc supports at most 16 arguments.

Note: The first argument must be a DynamicLibrary obtained from LoadLibrary() or a numeric module handle (nint/long). Passing a NativeLib script class instance directly to CallFunc is not supported use NativeLib.Invoke() instead.

NativeLib wrapper class

The NativeLib class wraps LoadLibrary + CallFunc into a clean, disposable object with auto-cleanup. Constructor loads the DLL, destructor frees it, Invoke() calls native functions with params:

// Usage var user32 = new NativeLib("user32"); var len = user32.Invoke("GetWindowTextLengthW", chatLog.Handle); user32.Invoke("Beep", 800, 200); // Auto-freed when variable goes out of scope // Or with array args user32.Invoke("Beep", [800, 200]);
The NativeLib class is available as a script include from assets/language/samples/native/nativelib.slc.
LoadLibrary(name) returns a DynamicLibrary that resolves function pointers automatically: kernel.Sleep(1000). It is a global, and so is FreeLibrary(lib).
Cipher AES-256-GCM encryption, plus post-quantum ML-KEM key exchange and ML-DSA signatures

The Cipher namespace provides AES-256-GCM authenticated encryption for string data, and the two post-quantum algorithms .NET 11 ships as stable: ML-KEM (FIPS 203, key encapsulation) and ML-DSA (FIPS 204, signatures). Symmetric keys and ciphertext are base64-encoded for storage and transport, with random 12-byte nonces and 16-byte authentication tags per encryption; the post-quantum members speak byte[], because a key pair is binary.

Cipher.GenerateKey()

Generates a random 256-bit key encoded in base64. Suitable for use with Encrypt and Decrypt.

var key = Cipher.GenerateKey();

Cipher.GenerateRandomToken(int sizeInBytes = 32)

Generates a random token of the specified byte size, encoded in base64. Default size is 32 bytes.

var token = Cipher.GenerateRandomToken(16);

Cipher.Encrypt(string data, string base64Key)

Encrypts the given string using AES-256-GCM with the provided base64-encoded key. Returns the combined nonce + tag + ciphertext as base64.

var enc = Cipher.Encrypt("secret data", key);

Cipher.Decrypt(string base64Cipher, string base64Key)

Decrypts the given base64 ciphertext (produced by Encrypt) using the same key. Throws on wrong key or tampered data.

var original = Cipher.Decrypt(enc, key);
// Full roundtrip var key = Cipher.GenerateKey(); var message = "Hello, secret world!"; var enc = Cipher.Encrypt(message, key); print(enc); // base64 ciphertext var dec = Cipher.Decrypt(enc, key); print(dec); // "Hello, secret world!"
Uses System.Security.Cryptography.AesGcm with 256-bit keys, 12-byte nonces, and 16-byte tags. Each Encrypt call generates a fresh random nonce, so the same plaintext encrypted twice produces different ciphertext.

Cipher.KemGenerate(string algorithm)

Generates an ML-KEM key pair, answering a dictionary with Algorithm, EncapsulationKey (the public half, 800, 1184 or 1568 bytes for ML-KEM-512, -768 or -1024) and DecapsulationKey (the secret half).

var pair = Cipher.KemGenerate("ML-KEM-768");

Cipher.KemEncapsulate(byte[] encapsulationKey, string algorithm)

Encapsulates a fresh shared secret against a peer's encapsulation key, answering Ciphertext (1088 bytes at 768) and SharedSecret (32 bytes). The ciphertext travels to the peer; the secret never does.

var box = Cipher.KemEncapsulate(pair["EncapsulationKey"], "ML-KEM-768");

Cipher.KemDecapsulate(byte[] decapsulationKey, byte[] ciphertext, string algorithm)

Recovers the same 32-byte shared secret from a ciphertext using the secret half of the pair. A ciphertext built for another key answers a different secret rather than an error, which is how ML-KEM is defined: compare the two secrets before trusting one.

var secret = Cipher.KemDecapsulate(pair["DecapsulationKey"], box["Ciphertext"], "ML-KEM-768");

Cipher.SignGenerate(string algorithm)

Generates an ML-DSA key pair, answering Algorithm, PublicKey and PrivateKey. The algorithm names are ML-DSA-44, ML-DSA-65 and ML-DSA-87.

var keys = Cipher.SignGenerate("ML-DSA-65");

Cipher.Sign(byte[] privateKey, byte[] message, string algorithm)

Signs a message, answering the signature bytes (2420, 3309 or 4627 for the three sizes). The message is bytes: Encoding.UTF8.GetBytes(text) for text, and the same bytes must be passed to Verify.

var sig = Cipher.Sign(keys["PrivateKey"], Encoding.UTF8.GetBytes("release 1.2.3"), "ML-DSA-65");

Cipher.Verify(byte[] publicKey, byte[] message, byte[] signature, string algorithm)

Answers true when the signature matches the message and the public key, false otherwise, including when a single byte of the message changed.

var ok = Cipher.Verify(keys["PublicKey"], Encoding.UTF8.GetBytes("release 1.2.3"), sig, "ML-DSA-65");
// Key exchange between two parties: only the encapsulation key is published var alice = Cipher.KemGenerate("ML-KEM-768"); var bob = Cipher.KemEncapsulate(alice["EncapsulationKey"], "ML-KEM-768"); print(bob["Ciphertext"].Length); // 1088, the bytes Bob sends back var mine = Cipher.KemDecapsulate(alice["DecapsulationKey"], bob["Ciphertext"], "ML-KEM-768"); print(mine.Length); // 32, and equal to bob["SharedSecret"] // The 32 bytes are a symmetric key: hand them to Cipher.Encrypt or to AesGcm
// A signature over a release note, and a check that the note was not altered var keys = Cipher.SignGenerate("ML-DSA-65"); var note = Encoding.UTF8.GetBytes("release 1.2.3"); var sig = Cipher.Sign(keys["PrivateKey"], note, "ML-DSA-65"); print(Cipher.Verify(keys["PublicKey"], note, sig, "ML-DSA-65")); // True note[0] = 82; // the same text with one byte changed print(Cipher.Verify(keys["PublicKey"], note, sig, "ML-DSA-65")); // False
The post-quantum members wrap System.Security.Cryptography.MLKem and MLDsa, so a key is standard FIPS 203/204 material. Two differences from the symmetric half are worth knowing: they speak byte[] rather than base64 strings, and an algorithm name is a NAME, so a wrong spelling is refused with the accepted ones printed. To store a key as text, Convert.ToBase64String(key["PrivateKey"]) and Convert.FromBase64String are the bridge. FIPS 205 (SlhDsa) is deliberately not offered: the platform marks it experimental, and a script surface does not rest on an API that may be removed.
GlobalHotKey Register global keyboard shortcuts via raw Win32 RegisterHotKey API

Register system-wide hotkeys that work even when the application is not in focus. Uses raw Win32 RegisterHotKey/UnregisterHotKey from user32.dll no WPF or Windows.Forms dependency. Requires a visible window handle (Form) to receive WM_HOTKEY messages.

Modifier constants

Combine with bitwise OR (|):

ConstantValueDescription
MOD_ALT0x0001Alt key
MOD_CTRL0x0002Ctrl key
MOD_SHIFT0x0004Shift key
MOD_WIN0x0008Windows key
MOD_NOREPEAT0x4000Fire callback only once per keypress (recommended)

Methods

Register(key, modifiers, callback)Register a hotkey. key is a string name ("A", "F1", "Space") or VK code (0x41). Returns non-zero id on success, 0 on failure.
Unregister(id)Unregister by id (returned from Register). Safe to call with invalid ids.
UnregisterAll()Unregister all hotkeys at once.
SetHandle(hwnd)Set the window handle to receive WM_HOTKEY messages. Call once with form.Handle before registering hotkeys.

Valid key names

Letters A-Z, digits 0-9, function keys F1-F24, arrows (Up/Down/Left/Right), Space, Enter, Escape, Tab, Back, Delete, Insert, Home, End, PageUp, PageDown, PrintScreen, Pause, numpad (NumPad0-NumPad9, Multiply, Add, Subtract, Divide, Decimal).

// Key name overload var mods = GlobalHotKey.MOD_ALT | GlobalHotKey.MOD_NOREPEAT; var id = GlobalHotKey.Register("S", mods, fun() { print("Alt+S pressed!"); }); // VK code overload var id2 = GlobalHotKey.Register(0x53, mods, fun() { print("Alt+S via VK code"); });
// Create a Form, register hotkeys, run message pump var form = Application.CreateForm("Hotkey Demo"); form.Show(); GlobalHotKey.SetHandle(form.Handle); // CTRL+A → show MessageBox GlobalHotKey.Register("A", GlobalHotKey.MOD_CTRL | GlobalHotKey.MOD_NOREPEAT, fun() { form.MessageBox("CTRL+A pressed!", "Hotkey", 0); }); // CTRL+Z → close the form GlobalHotKey.Register("Z", GlobalHotKey.MOD_CTRL | GlobalHotKey.MOD_NOREPEAT, fun() { form.SendMessage(0x0010, 0, 0); // WM_CLOSE }); Application.Run(form.Handle); GlobalHotKey.UnregisterAll();
Requirements: A visible Form window must exist and have a running message pump (Application.Run). Call SetHandle(form.Handle) before registering hotkeys. Without a window handle, Register returns 0. The callback fires synchronously on the message-pump thread.
Rect Create a Win32 RECT structure

Creates a Rect with the given Left, Top, Right and Bottom. Used with the Win32 window functions, and the same type every rect-returning call answers.

var r = Rect(10, 20, 100, 200);
// Get window dimensions into a Rect var rect = Rect(0, 0, 800, 600); print("Width: " + (rect.right - rect.left)); // Result: 800
Clipboard The desktop's clipboard text in one call, and the doors for a format the script assembles itself

The clipboard of the MACHINE rather than of a window, so a console tool copies as readily as a form. The text travels as CF_UNICODETEXT, and the whole recipe a correct write needs is the engine's: the MOVABLE global block the clipboard takes ownership of and frees itself, the payload as NUL-terminated UTF-16, the lock a read requires, and the release only when the handover failed.

MemberDescription
SetText(text)Replace the clipboard's text with this one, answering whether it landed.
GetText()The clipboard's text, or an empty string when it holds none.
Clear()Leave the clipboard empty, answering whether it could be opened.
Open([owner])Hold the clipboard, so the calls that follow can read or write ANY format. An owner window is optional (nothing owns it by default) and Close() must release it in a finally, because a script that leaves it held blocks every other process.
Close()Release the clipboard, handing it to the next process.
Empty()Discard what the clipboard holds, whatever its format.
SetData(format, hMem)Hand a block to the clipboard in the format the script names. The clipboard takes OWNERSHIP, so the block must come from Mem.Alloc and must NOT be freed by the caller; it answers the handle, or 0 when the handover failed (and then the block is still the caller's).
GetData(format)The block the clipboard holds in that format, as a handle to lock and read. The block belongs to the clipboard: lock it with Mem, and never free it.
Watch(control, handler), Unwatch(control)Be TOLD when the clipboard changes, instead of comparing GetText() on a timer: the handler is called with the watched control from the pump, on your thread. Watch answers whether the window was registered, Unwatch whether something was being watched, and a closed window drops its own registration.
// copy the log, then read it back: the second half must answer the first if (Clipboard.SetText(logText)) { print("copied " + logText.Length + " character(s)"); } else { print("the clipboard is held by another process"); } var back = Clipboard.GetText();

A failure is a VALUE and not an error, because another process holding the clipboard open is normal on a busy desktop: SetText answers false and GetText an empty string. An empty clipboard and one held elsewhere are the same answer to a reader, so a script that must tell them apart clears it first and checks what it reads.

TEXT is what the pair above covers, and the five doors cover the rest: another format (a dropped-file list, an image) is the script's own blob, handed over with SetData or read back with GetData while the clipboard is held open. The ownership rules a script must obey are on those rows, and they are the reason the pair above exists: a block the clipboard owns is easy to leak or to free twice.

Watching for changes: Clipboard.Watch, not a poll

Windows TELLS a window when the clipboard changes, so a watcher does not have to compare GetText() on a timer. Clipboard.Watch(control, handler) registers the window the control owns and answers whether it did; every change then calls the handler with that control, from the pump, on your thread. Clipboard.Unwatch(control) stops it and answers whether something was being watched, and the registration goes with the window when the window dies, so a closed form does not keep a handler alive.

// print the first text copied after the watch starts, then stop watching var watch = Application.CreateForm("clipboard watch"); // the window exists already (created, hidden): nothing to call here, and it is never shown var seen = [].ToList(); Clipboard.Watch(watch, fun(Control target) { seen.Add(Clipboard.GetText()); }); Clipboard.SetText("first"); for (var i = 0; i < 100 && seen.Count == 0; i = i + 1) { Application.DoEvents(); sleep(20); } print(seen.Count > 0 ? "arrived: " + seen[0] : "no notification arrived"); Clipboard.Unwatch(watch);

Three rules the shape needs. The listener belongs to a WINDOW, so the control must have one: Application.CreateForm creates it (hidden) before returning, so nothing has to be called to make one and a form that is never shown is enough. The handler runs INSIDE the pump, so it is on your thread and can call anything, the clipboard included. And clearing the clipboard is itself a change, so a watcher that runs a snippet and then empties the clipboard must ignore the event its own clear provokes, which is what comparing against the text it just handled answers.

assets/language/probes/clipboard_runner.slc is this watch as a working tool: leave it running in the REPL, copy any script text, and the snippet is executed with RunScript and shown in a dark, centred window whose log box fills it, with a Clear button, a Run in this session (global) check box and a status bar carrying the last run, with the same entry appended to clipboard_runs.log beside it and the clipboard emptied so one paste runs once. Its panel is a SECOND window and deliberately not the watched one: a displaced window procedure also displaces WM_COMMAND and WM_PAINT, so the panel keeps the engine's own procedure and only the hidden notification target is watched, which is what Clipboard.Watch now arranges itself.

Events A feed a script can hold: subscribe to it, publish from any thread, consume it with await foreach

A FEED is a value that carries events instead of owning them. A class event is the shortest way to say "this object tells you something", and it is the right door when the publisher is the object you hold. A feed covers the other shapes: handing the source of events to another function, publishing from a socket thread or a Process output callback while a subscriber writes a window, ending with a reason, and letting a consumer PULL rather than be called.

Values are object, so one feed carries lines, records, numbers or instances without a type per payload. Every subscriber has its own queue of a fixed capacity, so a slow subscriber cannot hold up a fast one and the memory a feed can hold does not grow with the traffic.

Creating one

CallWhat it makes
Create()A feed delivered inline, holding 1024 values per subscriber, dropping the oldest when one is full.
Create(mode)The shorthand for the common case: "inline" or "runThread".
Create({ mode: 'runThread', capacity: 256, overflow: 'block' })All three settings. A name this call does not know is REFUSED, naming the three it takes, so a typo cannot silently leave the default in place.

What a feed answers

MemberDescription
Subscribe(onNext [, onEnd])Call onNext for every value, and onEnd once when the feed ends: with an empty string for a normal end, with the reason after Fail. Answers a handle; a value that is not a function is refused by name.
Start(work [, state [, options]])Run work as the feed's PRODUCER on its own background thread, handing it the feed first and state second when one is given: a normal return ends the feed with Complete, and a script error is reported once and ends it with Fail, so a consumer learns why instead of waiting for an end that never comes. A function of no parameters, of the feed, or of the feed and a state value is accepted, and the state may be null when only options are wanted. The one option is sta: Start(work, null, { sta: true }) runs the body in a single-threaded apartment, which a body that drives COM needs (it refuses on an MTA thread), and it is the non-blocking counterpart of Task.RunSta, which waits for its body. This is what replaces ThreadPool.QueueUserWorkItem for a feed.
Next(value)Publish one value to every subscriber. Ignored once the feed has ended, which is what a producer that is a moment behind its consumer needs.
Complete(), Fail(reason)End the feed. A subscriber still gets the values already queued for it, then its onEnd.
Dispose()End the feed NOW: what is queued is dropped and no end handler runs. Usable as using var feed = Events.Create();
ReadOnlyA view of the same feed that can subscribe and cannot publish: Next, Complete and Fail are refused there, and its own Dispose does nothing, so a script can hand a feed to somebody else without handing over the right to publish on it.
Count, Subscribers, Closed, DroppedWhat is queued for the subscribers that have not been given it, how many are listening, whether the feed has ended, and how many values the capacity has cost. A pull loop (await foreach) COUNTS in Subscribers and not in Count, because it owns its own queue, which is what lets a producer wait for its consumer with while (feed.Subscribers == 0).
Mode, Capacity, OverflowThe three settings the feed was created with, as the names above.

A subscription is an ordinary IDisposable, so the engine's own using is the idiomatic unsubscribe and no Dispose() call is needed: using (var sub = feed.Subscribe(onLine)) { ... } disposes at the block's closing brace, and using var sub = feed.Subscribe(onLine); disposes at the end of the enclosing block, which is why the declaration form works inside a function. A read-only view's Dispose is a no-op on purpose, so using on a view is harmless.

Json.Serialize(feed) answers the feed's STATE: Mode, Capacity, Overflow, ReadOnly, Closed, Subscribers, Queued and Dropped. The subscribers are deliberately absent, because each is a closure over the run it was made in and nothing could rebuild one from JSON. A read-only view carries the same rows with ReadOnly: true, and Json.Serialize(subscription) answers Closed. Serializing a feed is how a tool reports what its pipelines are doing; it is not a way to move one, so a TYPED read into the type is refused by name (unknown type name 'Subject'): what comes back from JSON is the snapshot, as a dictionary. Serialize, read back, serialize again gives the same text, which is what makes a snapshot comparable across runs.

Where a delivery runs: inline or runThread

inline calls the subscriber on the thread that published, before Next returns. That is what a script publishing from its own statements expects, and it is the default.

runThread queues the value and delivers it on the thread the RUN began on, inside the engine's own pump: between statements, in Task.Wait and inside Application.Run, where a wake-up message makes the delivery prompt rather than waiting for the next mouse move. This is the mode for a producer on another thread: a subscriber that writes a control, or reads interpreter state, must run on the run thread, and a control write from a Process output callback does not land.

The setting is per FEED, not per subscriber, because it is about the source: a socket or a worker thread is runThread, and a value published from your own statement is inline.

Delivery follows the statement boundary, so a script that blocks inside one statement sees its feed when that statement ends. await foreach does not have that limitation: a pull consumer waits on the value itself.

Where a subscriber runs, and the one rule it owes

A subscriber runs on the RUN thread, never on the publisher's: that is what makes runThread safe for a UI, because the box a subscriber writes is the one the message loop owns. The rule that follows is that a subscriber must not pump. If it calls Application.DoEvents (or anything that waits and pumps, such as await) the next value is delivered INSIDE the current delivery, so an app that runs its work in a subscriber and waits there will start a second piece of work inside the first. Keep a subscriber short, and let the loop do the waiting.

Who publishes: feed.Start(work)

Most feeds have one producer, and Start owns the three things that spelling gets wrong when it is written by hand. It runs the body on its own background thread with the stack a run gets, so the run thread (and its window) stays responsive. It ends the feed for you: a normal return is Complete, and a script error is reported once in the engine log and becomes Fail(reason), where an escaping error in a ThreadPool body is fatal and no script can catch it. And it hands the feed to the body as its first parameter, so the producer can be a named function with nothing captured, with the caller's state arriving second exactly where the pool callback's own argument used to be.

What it does not do is abort the body: .NET has no thread abort, so a long-lived producer guards itself with while (!feed.Closed) { ... }, and a consumer that ends the feed stops it at its next check. Publishing from the producer thread is always safe; a subscriber that writes a control still needs runThread, which is the mode that moves the delivery to the run thread.

When a subscriber is too slow: overflow

PolicyWhat happens to a value that does not fit
'dropOldest'The oldest queued value goes, so a subscriber that catches up reads the NEWEST traffic. The default, and what a log or a price feed wants.
'dropNewest'The arriving value is dropped, so the oldest queued ones survive.
'block'The PUBLISHER waits for room, and after five seconds it gives up and drops the oldest instead, which keeps a dead consumer from stalling a producer for ever. A publisher that is itself on the run thread never waits, since the consumer it would be waiting for is that thread.

Every value a policy costs is counted in Dropped, so a script can tell "the consumer is behind" from "the source is quiet".

Pulling instead: await foreach

A feed is also an async sequence, so a consumer that would rather ask for the next value than be called can loop over it. Each consumer is a subscriber with its own queue, and the loop ends when the feed does; a break unsubscribes. A plain foreach is refused and names await foreach, because a feed has no end until it ends.

The rules worth knowing before using one

A feed is a BROADCAST, not a queue: a value published while nobody is listening is dropped. Start listening first, or keep the values yourself until the consumer arrives.

A subscriber that throws does not break the publisher: the failure is reported once, in the engine's log, and that subscriber is removed so one mistake cannot poison every later value.

A feed belongs to the INTERPRETER that created it, not to the run that happened to create it: in a session it stays open across .runs, and a producer started by one run is still ticking in the next one, and it is closed when that interpreter is disposed, which is also when a detached capture's own interpreter goes away. That is what makes Dispose the script's own way to end a producer early, and it is why a producer that must not outlive its work guards with while (!feed.Closed).

// a worker thread publishes, the window shows the lines: runThread is what makes the control write legal var form = Application.CreateForm("feed"); var box = form.CreateTextBox("", 8, 8, 620, 320); var feed = Events.Create("runThread"); var sub = feed.Subscribe(fun(object line) { box.AppendText("" + line + "\r\n"); }); // the producer receives the feed and runs off the run thread; a normal return ends the feed feed.Start(fun(EventSubject feed) { foreach (var name in Directory.GetFiles(".")) { feed.Next(name); } }); form.Show(); Application.RunFor(1500, form); print("closed by the producer: " + feed.Closed + ", subscribers: " + feed.Subscribers); sub.Dispose();
// pulling: a consumer that asks for the next value instead of being called var lines = Events.Create("runThread"); lines.Start(fun(EventSubject feed) { // the loop attaches when it starts, and a value with no subscriber is dropped: wait for it while (feed.Subscribers == 0) { sleep(5); } for (var i = 1; i <= 3; i = i + 1) { feed.Next(i * 10); sleep(20); } }); await foreach (var value in lines) { print(value); }

The two shapes share one feed, one set of refusals and one bounded queue, so a script can start with Subscribe and move to await foreach without changing how values reach it.

Mem Raw unmanaged buffer access named byte/word accessors, bulk fill, hex dump, disposable buffers

Safe, modern descendants of the classic BASIC PEEK/POKE. Operates only on buffers the script allocated itself (Mem.Alloc / Marshal.AllocHGlobal); there is intentionally no absolute-address byte access (antiquated and dangerous on modern virtual-memory OSes). All buffers are raw pointer values (long) or disposable wrappers.

Buffer lifecycle

var buf = Mem.Alloc(16); // unmanaged 16 bytes, returns a pointer (long) Mem.Free(buf); // release (required when done) print(Mem.LiveBuffers()); // number of live Mem.Buffer wrappers (leak proof)
// Auto-free with using no explicit Mem.Free needed using (var b = Mem.Buffer(64)) { Mem.WriteByte(b.Ptr, 0, 0xAB); print(Mem.ReadByte(b.Ptr, 0)); // 171 } // b.Dispose() frees the buffer automatically

Named byte/word accessors (the PEEK/POKE width)

MethodDescription
ReadByte(ptr[, offset])Read one byte the true PEEK
WriteByte(ptr, value[, offset])Write one byte the true POKE
ReadInt16(ptr[, offset]) / WriteInt16(ptr, value[, offset])16-bit little-endian read/write
ReadInt32(ptr[, offset]) / WriteInt32(ptr, value[, offset])32-bit read/write
ReadInt64(ptr[, offset]) / WriteInt64(ptr, value[, offset])64-bit read/write
ReadString(ptr)UTF-16 string read (Marshal.PtrToStringUni)
ToPointer(text) / FreePointer(ptr)Allocate/free the UTF-16 copy of a string, which is what a native call wanting a wchar_t* takes. The pointer is the caller's to free.

Offset form: the two-argument write forms treat the 2nd arg as the value at offset 0; the three-argument form is (ptr, offset, value). When no offset is given, offset 0 is used.

Bulk operations

Mem.Fill(ptr, length, value); // memset the POKE-loop replacement var dump = Mem.Dump(ptr, length[, bytesPerRow]); // hex + ASCII inspection
// Fill a 200 MB buffer with 0xFF, then hex-dump the first 16 bytes var buf = Mem.Alloc(200 * 1024 * 1024); Mem.Fill(buf, 200 * 1024 * 1024, 0xFF); print(Mem.Dump(buf, 16, 8)); Mem.Free(buf);
Leak detection: unmanaged buffers are invisible to GC.GetTotalMemory. Use GC.PrivateMemory() / GC.WorkingSet() to detect unmanaged leaks (see the GC entry). Mem.LiveBuffers() returns the count of Mem.Buffer wrappers still allocated the direct proof that every using / using var scope released its pointer. using (var b = Mem.Buffer(n)) auto-frees on block exit, even on exception; using var b = Mem.Buffer(n) frees at enclosing scope exit (see the using entry). To release a wrapped buffer manually, call b.Free() (alias of b.Dispose()): it frees the pointer, zeroes b.Ptr, and decrements LiveBuffers() double-call safe. Do not call the raw Mem.Free(b.Ptr) on a wrapped buffer: it frees the bytes but leaves the wrapper counting it (counter stays elevated).
GC Garbage collection control

Provides .NET GC metrics and control collect memory, query usage, and inspect generation counts.

GC.Collect(); GC.CollectAsync([gen]); // non-blocking collect GC.GetTotalMemory(); GC.GetTotalMemoryFormatted(); GC.GetAllocatedBytes(); // thread allocated GC.GetAllocatedBytesFormatted(); GC.GetGeneration(obj); GC.GetCollectionCount(gen); GC.GetMemoryInfo(); // GC memory status GC.GetMemoryInfoFormatted(); GC.GetTotalPauseDuration(); GC.WaitForFinalizers(); GC.SuppressFinalize(obj); GC.ReRegisterForFinalize(obj); GC.Cleanup(); GC.MaxGeneration; GC.WorkingSet(); // OS resident bytes (long) GC.PrivateMemory(); // OS committed private bytes (long) the reliable signal for unmanaged buffers GC.TrimMemory(); // trim the process working set (EmptyWorkingSet) the OS pages out the GC's reserved-but-idle segments
print("Memory: " + GC.GetTotalMemory()); GC.Collect(); print("After GC: " + GC.GetTotalMemory()); print("Gen 0 collections: " + GC.GetCollectionCount(0)); // After a bursty run (big collections, benches): GC.Collect compacts the managed heap but the // GC keeps its reserved segments committed, so the process RAM stays high. TrimMemory() asks // the OS to page those idle pages out the managed heap is untouched. The REPL's .gc collect // does this automatically. GC.TrimMemory();
Avro Avro 1.12 schemas, the binary and JSON encodings, container files and schema generation

Avro is Avro 1.12.0: the schema model, the Parsing Canonical Form with its fingerprints, the binary encoding, the Avro JSON encoding, container files with their codecs, and a schema GENERATED from a script type. It is a namespace of its own rather than a corner of Json, because a schema is JSON but the surface is Avro's, and Avro.Serialize(...) says what a reader needs. Avro RPC and avrogen code generation are deliberately absent: a script is not an RPC peer, and generated C# source is not something this engine runs.

Avro.Parse(schema) // the .avsc text, normalized Avro.Validate(schema) // true when Parse would accept it Avro.Canonical(schema) // the Parsing Canonical Form Avro.Fingerprint(schema [, algorithm]) // crc-64-avro (default), sha-256, md5 Avro.Serialize(value, schema) // the Avro binary encoding, as a byte[] Avro.Deserialize([type,] data, schema) // ... back, as a dictionary or the type named Avro.Deserialize<T>(data, schema) // the same, with the type as a TYPE ARGUMENT Avro.RoundTrip([type,] value, schema) // what the engine reads back from a value it wrote Avro.SerializeJson(value, schema) // the Avro JSON encoding, as text Avro.DeserializeJson([type,] json, schema) // ... back Avro.Schema(type [, options]) // .avsc text GENERATED from a class, struct or enum Avro.WriteContainer(records, schema [, options]) // a whole .avro file: magic, metadata, blocks Avro.ReadContainer([type,] data) // every object of a container, in order Avro.ContainerSchema(data) // the .avsc text the FILE carries, verbatim Avro.ContainerJson(data [, options]) // every record as PURE JSON, decompressed with its own codec Avro.AppendContainer(data, records) // INSERT: one new block, ended with the file's own sync Avro.UpdateContainer([type,] data, predicate, transform) // UPDATE: a REWRITE, where the predicate selects Avro.DeleteContainer([type,] data, predicate) // DELETE: a REWRITE, every record the predicate selects // THE TYPE LEADS wherever a member takes one, exactly as Json.Deserialize(type, payload) puts it // first, and the ARITY says it is there: Deserialize(data, schema) is the untyped read, and // Deserialize(Row, data, schema) the typed one.

A schema is JSON text, a { } literal, a [ ] union literal, a script class or struct instance, or a type a session declares. Schema takes a TYPE or an instance and refuses schema text on purpose, naming Parse, so one member never means two opposite things. A value is a script dictionary, class or struct instance, a list or array, or a scalar, with the members matched to the schema's field names.

var schema = '{"type":"record","name":"User","fields":[{"name":"id","type":"long"},{"name":"name","type":"string"}]}'; var bytes = Avro.Serialize({ "id": 7, "name": "bob" }, schema); print(bytes.Length); // 5 print(Json.Serialize(Avro.Deserialize(bytes, schema))); // {"id":7,"name":"bob"} print(Avro.Fingerprint(schema)); // 9252cb7c3e90675e // The other direction: a script type declares the shape once, and the schema follows it. class DocLine { public string Sku = ""; public int Qty; } print(Avro.Schema(DocLine)); // {"type":"record","name":"DocLine","fields":[{"name":"Sku","type":"string"},{"name":"Qty","type":"int"}]}

RoundTrip is those two calls composed: it writes the value and reads it back through the SAME schema, so its answer is the schema's reading of the value (a class instance comes back as its dictionary, a logical type as its script type), which is what a compatibility check wants. Its optional LEADING argument is Deserialize's typed door, so it can answer a class or struct directly, and a value that does not fit is refused by Serialize's own rule, naming the field. The type leads here too, and the arity is what says it is present: Avro.RoundTrip("hi", '"string"') is a string VALUE, where Avro.RoundTrip(Row, {...}, schema) is a typed read.

Avro.Deserialize<T>(data, schema) is that typed door spelled with a type argument, exactly as Json.Deserialize<T> spells it: the class or struct is written where the call is, so a name that does not exist is refused at the call rather than arriving as a string at run time. It is the same read and the same reconstruction, never a second implementation, so the positional and the type-argument spellings answer the same object.

Which encoding for which job

Binary (Serialize/Deserialize) is the compact wire form: a zig-zag varint for int and long, raw bits for float and double, a length prefix for bytes and string, block counts for arrays and maps, and a long index for a union branch. A bytes or fixed value is a real byte[], which is what Encoding.UTF8.GetBytes answers and what a script list is not. JSON (SerializeJson/DeserializeJson) is the spec's JSON encoding: a union wraps its branch by name ({"string":"hi"}, and a bare null for the null branch), and bytes and fixed travel as ISO-8859-1 strings. Canonical and Fingerprint are the schema's identity: two peers agree on a schema when their fingerprints match, without exchanging the text.

// the value a schema says, from the three sides Avro.SerializeJson(null, '["null","int"]') // null Avro.SerializeJson(5, '["null","int"]') // {"int":5} Avro.Canonical('{"type":"record","name":"R","namespace":"n","doc":"x","fields":[{"name":"f","type":"int"}]}') // {"name":"n.R","type":"record","fields":[{"name":"f","type":"int"}]} doc and the short name are gone

Logical types and generated schemas

A logical type maps onto a script type rather than onto its base type: decimal is a script decimal (its precision and scale come from the schema, or from decimalPrecision/decimalScale when a schema is generated), uuid is a Guid or its text, date and timestamp-millis/-micros are a DateTime (a timestamp reads back as UTC), and time-millis/-micros are a TimeSpan. Avro's JSON encoding has no logical forms, so the JSON members refuse one by name and point at Serialize. A generated schema maps a class or a struct to a record, an enum to an enum, T? to ["null", T] with a null default, a List or Dictionary to an array or a map, Guid to uuid, DateTime to timestamp-millis, TimeSpan to time-micros, decimal to bytes plus decimal, and a byte[] to bytes. An object member has no schema: Avro needs a type to write, so it is refused rather than guessed, and the refusal says so.

The options are namespace, decimalPrecision, decimalScale, codec and recordName, as a dictionary literal or as JSON text; an unknown key is refused with that list. codec names a container's compression, and this engine writes null, deflate, snappy, zstandard, gzip and brotli while bzip2 and xz are refused by name rather than written unreadable. The container section below says which of the six a reader other than this engine can open, because gzip and brotli are AvroConvert's own extensions rather than spec codecs.

Container files and their codecs

A container is a stream of objects with ONE schema in its header: the spec's magic, a metadata map carrying avro.schema and avro.codec, a 16-byte sync marker, then blocks of objects each ended by the same marker. WriteContainer takes the records and an options dictionary whose codec is null, deflate (raw DEFLATE, no zlib wrapper), snappy (a Snappy block plus the CRC-32 of the uncompressed data, which the reader verifies), zstandard (a standard Zstandard frame, written and read by the runtime's own ZstandardStream, which is the frame google/zstd writes), gzip or brotli. The last two are NOT Avro spec codecs: AvroConvert defines its own two that way, so a file carrying them is readable by these two tools and not by a strict Avro reader, while null, deflate, snappy and zstandard travel everywhere. A container can also be read LAZILY, and the type NAME is what says so, the same rule Json.Deserialize("Iterable", ...) follows: Avro.ReadContainer("Iterable", file) answers a VIEW over the file's bytes instead of a list of decoded records. The header is parsed once, so the schema and the codec are known, the block boundaries are recorded without decompressing anything, and Count is the sum of the blocks' own counts; a record is decoded the first time it is READ, so a million-record file costs its bytes plus the records a script actually touches. IEnumerable is the same door, and an element name ("Iterable<DocLine>") imposes that type on each record as it is decoded, exactly as a lazy JSON list imposes its element name. The value is a view, so every mutation is refused by name: read a copy without the name to edit one. Reading it eagerly is Avro.ReadContainer(file), which decodes every record before it answers.

A container can be EDITED, and the FORMAT decides how far each verb goes. Avro.AppendContainer(data, records) is the one edit that happens in place: records are read back in block order, so a new record is a new BLOCK after the last one, ended with the file's own 16-byte sync marker (a fresh one would make every reader refuse the file as corrupt), and nothing already written is decoded, decompressed or re-encoded. An UPDATE or a DELETE cannot happen where a record sits: a record is variable-length inside a usually compressed block with no index, so Avro.UpdateContainer([type,] data, predicate, transform) and Avro.DeleteContainer([type,] data, predicate) are REWRITES. Both decode the records, let the caller's functions decide, and write the kept set again into the file's own HEADER, byte for byte: the schema, the codec and the sync marker are copied over, so a rewritten file is still the same container and still appends and reads. What that costs is the whole set re-encoded into one block, which is the price of an edit, and the reason the lazy read exists for a walk. ReadContainer needs nothing but the bytes, because the schema travels in the file, and its optional LEADING argument is the typed door records come back through. bzip2 and xz are refused by name rather than written in an encoding no reader here could open.

var rows = everyOrder; // a script list var file = Avro.WriteContainer(rows, schema, { "codec": "deflate" }); print(Avro.ReadContainer(file).Count); // the object count, each one decoded with the header's schema // The same 200 repeated records: 5907 bytes with "null", 638 with "deflate", 1189 with "snappy", // 459 with "zstandard", 653 with "gzip", 511 with "brotli". The last two are AvroConvert's own // extensions, so they buy bytes and cost portability; the rest travel to any Avro reader.
var lazy = Avro.ReadContainer("Iterable", file); print(typeof(lazy)); // Iterable print(lazy.Count); // 200, from the blocks' own counts, nothing decompressed print(Json.Serialize(lazy[0])); // the first record, decoded only now

A stored container describes ITSELF, and these are the two members a reader of a file or a BLOB wants: Avro.ContainerSchema(data) answers the .avsc text the file carries in its header (verbatim, not a re-serialization of the parsed schema), and Avro.ContainerJson(data [, options]) answers every record as a JSON array, decoded with that schema and DECOMPRESSED with the codec the file declares. That JSON is what SQLite's own json_extract, json_each and json_group_array read, so a container stored as a BLOB is queryable without leaving SQL: the same two answers are the SQL functions slc_avro_schema(blob) and slc_avro_json(blob). A bytes or fixed field renders as an ARRAY OF NUMBERS, which is this engine's convention for a byte[]. The one option is { "pretty": true } (or a bare true), which changes the layout and not the content.

var stored = File.ReadAllBytes("./orders.avro"); print(Avro.ContainerSchema(stored)); // the .avsc the file carries, which is what Avro.Schema wrote print(Avro.ContainerJson(stored)); // [{"id":1,...},{"id":2,...}], the codec decompressed here print(Json.Parse(Avro.ContainerJson(stored, { "pretty": true })).Count); // 2
// INSERT: one more record, one more block, the same header var grown = Avro.AppendContainer(file, [{ "id": 3, "name": "cara" }]); // UPDATE and DELETE: a rewrite that keeps the schema, the codec and the sync var renamed = Avro.UpdateContainer(file, (r) => r["id"] == 2, (r) => { return { "id": r["id"], "name": "BOB" }; }); var fewer = Avro.DeleteContainer(file, (r) => r["id"] == 1);

A benchmark beside the suite, bench_avro.slc, measures the shape AvroConvert's own table uses (1 000 users with a nested contact and two offerings): Avro binary is 74,386 bytes against 221,340 characters of Json.Serialize (33%), and the same records are 75,019 bytes as a null container, 14,669 with deflate, 26,675 with snappy, 7,358 with zstandard, 14,684 with gzip and 9,044 with brotli. It prints its timings, allocations and asserts only the structural half, because a duration is not a condition a suite can carry.

The same suite measures a SECOND model: the one the C# Corner article about Avro in .NET publishes its own table with, a User of int Id, bool IsActive, a 36-character Name, int Age, a nested Contact and two Offerings carrying a Guid. It prints that article's published row beside ours, because two libraries' tables are only comparable on ONE model. With 1 000 records our JSON text is 555.7 kB against the article's 759.94, Avro 308.2 against 440.76, JSON+gzip 151.4 against 286.56, JSON+brotli 142.8 against 262.59, Avro+gzip 134.8 against 261.87 and Avro+brotli 130.2 against 245.29, with Avro+zstandard at 131.4, which that article does not publish. The absolute sizes differ because the data is generated here (deterministic 36-character GUID text, the width and shape AutoFixture produces) while the article's came from AutoFixture itself, so the RATIOS are what compare: Avro alone is 55% of JSON here against 58% there, and Avro+brotli is 91% of JSON+brotli here against 93% there. JSON+gzip and JSON+brotli have no timing of their own, and their SIZE is derived from a one-field bytes container with its header subtracted, because the engine has no script-facing byte compressor.

What is refused, and why that is the useful half

A value that does not fit its schema is refused with the fact a writer needs: a record that omits a field names the field and what the value does have (a default is what a READER fills, never what a writer skips), a member the schema does not declare is refused instead of dropped, a number too wide for an int is refused with the 32-bit range rather than truncated, a value matching no union branch names the branches, an undeclared enum symbol names the symbols, a fixed of the wrong length names both counts, and data left over after Deserialize is refused with its offset, because that means the schema is not the one the bytes were written with. A malformed schema is refused the same way: a forward reference, a duplicate full name, field or symbol, an empty enum or a fixed without a size, a decimal without a precision or with a scale past it, and JSON that is not a schema at all. Every one of those sentences names the rule and what to change, so a schema bug is read rather than hunted.

Json JSON serialization, deserialization with typed reconstruction

Built on System.Text.Json with AOT-safe Utf8JsonWriter/Utf8JsonReader (no reflection). Serializes any interpreter-compatible value and parses JSON back into script objects. Supports typed reconstruction of class and struct instances via Deserialize.

An engine object serializes as what it is, one arm per kind rather than by reflection: an AOT image trims what a reflection walk would have found, so every namespace used to serialize as the type name "Namespace". A namespace answers its own surface, a Form its document, a script class its fields, and a value with no shape of its own the name a script writes for it, never a CLR type name:

var Z = Bytecode.LoadNamespace(one.Bytes, "What"); print(Json.Serialize(Z)); // {"Name":"What","Namespaces":{"A":{"Name":"A","Functions":["add"]}}, // "Properties":["What","__meta"]} the label a load gave it is listed, never walked into

Serialization primitives & collections

Json.Serialize(42); // "42" Json.Serialize(true); // "true" Json.Serialize("hello"); // '"hello"' Json.Serialize(null); // "null" Json.Stringify(value, true); // pretty-print Json.Deserialize<Dictionary<string, object>>(Json.Serialize(value)); // the raw JSON view, as one call

What Serialize returns, and why a nested result looks escaped

Json.Serialize returns a string (its typeof is string), not a JSON value. So handing its result to something that serializes again encodes it twice: the inner call turns the object into text, and the outer one then encodes that text as a JSON string, which by the JSON rules cannot hold a bare " and must write \". The backslashes exist only in the outer text; parse the envelope once and the value is the JSON text you wrote, with real quotes.

// a host that wraps a script's return value in its own JSON envelope Json.Serialize({ "ReturnValue": Json.Serialize(Build()) }); // {"ReturnValue":"{\"X\":3,\"Y\":4}"} text inside text Json.Serialize({ "ReturnValue": Build() }); // {"ReturnValue":{"X":3,"Y":4}} one object, one encoding

So return the value, not its serialization, wherever something else will serialize the answer: the value of a return that a host reads (a SQLite slc_file call, an MCP tool result, an HTTP JSON body, a form document row). The nested call is worth writing only when the consumer wants text: storing into a TEXT column, appending to a log, or printing it. Then the escapes are the correct JSON for a string, and a reader gets the object back by parsing a second time. Json.Stringify behaves the same way (it is a string too), and Json.SerializeToUtf8Bytes is the same encoding as bytes.

Serialization classes & structs

Class and struct instances serialize as flat JSON by default (public fields only, no type metadata). CLR types (like ErrorInfo, CancelEventArgs) also serialize without __type by default pass {"showType": true} to include type metadata for round-trip deserialization:

Json.Serialize(person); // {"name":"John","age":30}

Options are passed via a dictionary: the literal spelling ({"pretty": true}) and an options bag read from JSON both work. Keys are names, so they follow the interpreter's case rule like every other name the spelling the option is declared with in the default C#-strict mode, any case under the REPL's .lax. A key that does not match is reported as a warning and dropped, so neither a typo nor a differently-cased key can quietly become default output. includeNonPublic and nonPublic are two different modes, not two spellings of one: the first adds the non-public members to the public view, the second replaces it so a payload meant to show the non-public side does not have to filter its own output.

Because Json.Deserialize takes no options of its own and returns a dictionary, an options bag can be written as JSON too: Json.Serialize(x, Json.Deserialize('{"showType":true}')). That is the pattern crash_json_serialize.slc uses options read as data, and a typo is visible in the literal.

// A misspelled key is reported, not swallowed, and the keys that were understood still apply Json.Serialize(person, Json.Deserialize('{"showType":true,"typ":true}')); // [hh:mm:ss.mmm] [WARNING] Script: Json.Serialize: ignoring unknown option 'typ'. Valid options: // includeNonPublic, nonPublic, includeType, showType, pretty, omitDefaults. // → {"__type":"Person","name":"John","age":30} (showType still applied) Json.Serialize(person, Json.Deserialize('{"showTyp":true}')); // → {"name":"John","age":30} the same warning names showTyp, which is why the tag is missing
var opts = new Dictionary<string, object>(); opts["includeType"] = true; // {"__type":"Person","name":"John","age":30} the same marker as showType opts["includeNonPublic"] = true; // public AND private/protected fields opts["nonPublic"] = true; // ONLY the non-public ones the complement of the line above opts["showType"] = true; // {"__type":"Person","name":"John","age":30} script classes & structs too opts["omitDefaults"] = true; // only the fields whose value is not their TYPE's default // Native: Json.RoundTrip("hello") → "hello" (serialize + deserialize with __type) // Script-level helper alias (optional): var RoundTrip = (val) => { return Json.RoundTrip(val); }; opts["pretty"] = true; // multi-line indented output Json.Serialize(person, opts);

omitDefaults applies to a script class or struct field whose value is its TYPE's default (0, false, "", or null), so an object that sets a few of its fields emits only those. A field whose declared initializer DIFFERS from the type default is not omitted, because the test is against the type. What is left out reads back as the default it was, exactly, since Deserialize fills an absent key with that same value. A DICTIONARY entry and an ARRAY element are never omitted: there a zero is data or a position, not a default. The comparison is exact, so a 1e-7 is not a zero, and a non-default object is emitted whole. A dictionary ENTRY is a key/value pair rather than a property, so it is never omitted; a dictionary VALUED FIELD that is null goes like any other property, while an EMPTY one does not; and an object held in an object field has its own fields treated by the same rule. That is .NET's WhenWritingDefault condition, spelled as one option.

Serialization a form and its controls

A form, or any control, serializes as its property table: an array of rows, each {"Name":..., "Type":..., "Value":...}, which is the same table ctrl.PropList() answers, followed by the members the control's OWN kind adds (Theme and the palette, Padding, GridSize, and so on, which the base table cannot carry). A control made with CreateWinControl also reports ClassName, Style and ExStyle, which is what it takes to make that window again.

The form's children follow under a Controls row of type list, and each entry is ITSELF a row, so the same triple exists at every depth: {"Name":"Button1","Type":"Button","Value":[ ...the child's rows... ]}. The entry carries the child's IDENTITY, which is why the child's own rows do not repeat it: every control in the document therefore has a name, the one the script set or <Kind><n> counted per kind among its siblings, and the name and the kind each appear once. The ROOT is the exception and has to be, because nothing above it names it: its own rows carry Name and Kind.

The root also states the LAYOUT's version, as its first row: {"Name":"Version","Type":"int","Value":1}. Kind says which host a document is and Version says which layout of it, so a document written by a NEWER engine is refused by name instead of being mis-read, while a version older than this one, and a document with no such row at all (the layout that predates it), is read normally. Only a document ROOT carries it: a child's rows and a document window's rows are part of the same document, and Json.Serialize of a bare control is a fragment of one rather than a document, so it claims no version.

A form also publishes the CLIENT area its layout was designed in, as ClientWidth and ClientHeight. They are in DESIGN units, which are the units of Left, Top, Width and Height and so of every child's geometry, and they are the one pair of rows a document states that a reader cannot set: the document says the room its layout was laid out against, so a script can CHECK that the window it rebuilt has the same room instead of assuming it, which is what a different frame changes (another monitor's DPI, another theme). A control that is not a form has the two members but not the rows, because a form is what lays children out.

An MDI frame and an MDI document window are HOSTS too, and they write the same document: the frame's root says Kind: "MdiForm" and it carries its own controls under Controls and its DOCUMENT WINDOWS under MdiChildren, each of which nests its own Controls, so a frame's whole tree travels. Neither is a Control, so before this they answered a flat object of their public members, with a handle in it and no kind at all. READING one back is what Application.FormFromJson does, and it builds WHICHEVER host the root names: a frame comes back with its document windows, each window with its own controls, and a document whose root is a single MdiChild gets an implicit frame to be parented to (a window belongs to an MDI client, and a client to a frame).

The TYPE column carries a name a SCRIPT can write, and it is as precise as the control makes possible: a scalar's name (int, bool, string, color), a registered type's (ThemeMode), a nullable's (uint?), and a list's ELEMENT type where it is known (List<string> for the item texts of a ListBox or a ComboBox, List<ControlProp> for the children of a form, whose entries are the same rows one depth down). The spelling is the engine's own, so typeof of those value answers List and List<int> is written the same way; a list whose elements were not fixed stays a bare List.

Application.FormToJson(form) writes that document and Application.FormFromJson(doc) builds a NEW form from it, its title and its controls included, and answers how many controls were created. Building is the only direction: the document becomes a fresh host (a form, an MDI frame or a document window, whichever the root names) rather than being re-applied to one a script already holds, so a form a script wants to change is changed through its own members. The pair is what makes a stored form a reusable TEMPLATE: write the document to a database, read it back, and get a live form with the same controls and the same properties. FormToJson is Json.Serialize on the same value, so a control writes one format either way. A row whose property cannot be written is a fact the document merely REPORTS (ClassName, ItemCount, ColumnCount, TabCount, ClientWidth, ClientHeight) and is skipped; any other row the control does not carry is refused by name rather than dropped. An EVENT HANDLER is not in the document and cannot be: a handler is a closure over the interpreter that made it, so serializing one answers megabytes rather than a value (one handler is about 3.8 million characters, against two thousand for a whole form) and it would mean nothing in the process that read the document back. The document carries the names instead, which is what the index is for: a template is the LOOK, and the behaviour is re-attached to it by name (copy["Button1"].Click = ...).

var src = Application.CreateForm("template"); src.Theme = ThemeMode.Custom; src.ThemeBackground = 0x203040; var ok = src.CreateButton("OK", 10, 10, 80, 24); // the row a template table would hold, and a form built back out of it var doc = Application.FormToJson(src); var copy = Application.FormFromJson(doc); print(Application.FormToJson(copy) == doc); // True, at every depth

Typed deserialization

Json.Deserialize("Name", json) maps the payload onto Name, and Json.Deserialize<T>(json) is the same thing with the type as a type argument. The name is not advisory: it has to resolve, and it has to agree with the payload's shape "List<int>" and "IList" want a JSON array (they promise indexing), "Dictionary<string, int>" wants a JSON object, "HashSet" builds a set from an array, "Tuple" takes a positional array, and "Iterable" and "IEnumerable" accept either shape, because that is what those collection predicates mean everywhere else in the language. A declared member type is imposed inside the container as well: Dictionary<string, Person> gives Person values and HashSet<Person> holds them, while a base-type member (int) has nothing to impose. Every spelling the string name, the type argument, and the untyped form that infers from __type reaches one implementation, so they agree. A declared scalar is imposed, not merely tolerated: JSON numbers arrive as long, so List<int> hands back ints, and the conversion is the engine's own (the one behind Result.As<T>(), so 1.5 rounds to 2 and an overflowing value wraps, as unchecked arithmetic does). object means leave the payload as parsed, and a scalar payload that cannot become the named type says which payload it was rather than reporting the name as unknown. A name that resolves to nothing, or one whose shape the payload contradicts, is an error rather than a silent surprise.

// The name and the payload must agree Json.Deserialize("List<int>", '[1,2]'); // a typed list Json.Deserialize("Iterable", '{"a":1}'); // the dictionary Iterable takes either shape Json.Deserialize("Nonsense", '{"a":1}'); // error: unknown type name Json.Deserialize("Dictionary<string, int>", '[1,2]'); // error: array vs a dictionary name // The generic spelling, where the target is a plain class Json.Deserialize<Order>('{"Id":1042}'); // an Order // A type argument that is itself generic works too, and returns what the name form returns: Json.Deserialize<List<int>>('[1,2]'); // as "List<int>" above // Tuples are positional Json.Serialize((1,"a")) is [1,"a"] and the LABELS come from the type // argument, so a tuple's fields are reachable by name, not only as Item1/Item2: var pairs = Json.Deserialize<List<(string s, int i)>>('[["a",1]]'); print(pairs[0].s + "/" + pairs[0].i); // a/1 Json.Deserialize<(string s, int i)>('["a",1]'); // a Tuple as well the bare form works too // An element may name any supported type, containers included: var pair = Json.Deserialize<(int i, Iterable it)>('[1,[2,3]]'); print(pair.i + "/" + pair.it.Count); // 1/2

showType round-trip reference

showType: false (current default) clean output, no __type metadata. For round-trip with CLR types, use the typed Json.Deserialize("TypeName", json) overload.

showType: true includes __type in the output, enabling universal Json.Deserialize(json) auto-dispatch to reconstruct CLR types.

Containers carry a tag too. An object has a member slot for __type, so a dictionary simply gains one: {"__type":"Dictionary","k":1}. A JSON array has no member slot, so a list, tuple or array is wrapped {"__type":"List<string>","Values":["a","b"]}, {"__type":"int[]","Values":[1,2]}. A tuple also carries its labels beside Values {"__type":"Tuple","Names":["s","i"],"Values":["x",3]} because an array has nowhere to put them. The name is the one typeof gives (string[], List<string>, Dictionary, Tuple), and a HashSet is a container too: {"__type":"HashSet<int>","Values":[1,2]}.

A value the engine serves through an INTERNAL class is written by the ROOT of the collection it stands for. The list a typed Json.Deserialize hands back carries the declaration the read was asked for in typeof (List<int>, string[], IList), and its marker is the plain List, the way any other list is written, because the marker names the SHAPE a reader rebuilds and the element type is the wrapper's own business. The same rule covers whatever wrapper comes next, and is LazyDeserializedList still answers.

A dictionary's marker is metadata, not one of its entries. {"__type":"Dictionary<string, int>","k":1} reads back as the single entry k, untyped and typed alike, and a __type key holding anything that is not a container name is ordinary data and is kept. The parser rebuilds what was tagged, so Json.Parse(Json.Serialize(x, opts)) keeps the shape it had before tagging: a list comes back a list, and a tuple comes back a Tuple with its labels. A class instance with a field literally called Values is not affected the unwrap happens only when the type name is a container name.

// A real payload: an order with a list of lines and a totals dictionary class Line { public string Sku; public int Qty; } class Order { public int Id; public List<Line> Lines; public Dictionary<string, int> Totals; } // o = Order 1042, lines A-1×2 and B-7×5, totals {"qty": 7} Json.Serialize(o); // default: clean, no metadata // {"Id":1042,"Lines":[{"Sku":"A-1","Qty":2},{"Sku":"B-7","Qty":5}],"Totals":{"qty":7}} var opts = new Dictionary<string, object>(); opts["showType"] = true; Json.Serialize(o, opts); // the same payload, self-describing // {"__type":"Order","Id":1042, // "Lines":{"__type":"List","Values":[{"__type":"Line","Sku":"A-1","Qty":2}, // {"__type":"Line","Sku":"B-7","Qty":5}]}, // "Totals":{"__type":"Dictionary<string, int>","qty":7}} // ↑ three shapes in one payload: the object tags itself as a member, the list needs the // Values wrapper (an array has no member slot), and the dictionary's tag is just another // key. A container's tag is the name typeof gives it, and a callable is tagged "Function" // with its signature beside the marker (a JSON string has no member slot of its own). var typed = Json.Serialize(o, opts); Json.Deserialize(typed); // Order auto-dispatch through __type var strict = Json.Deserialize("Order", typed); // strict.Id == 1042, strict.Lines is a List with 2 items, strict.Totals is a Dictionary // the wrappers are unwrapped, so the containers come back as containers and not as the // {"__type":…,"Values":…} objects that carried them.
Can auto-roundtrip without showTypeNeeds showType: true
Primitives int, string, bool, nullCLR types in JsonTypeMap (CancelEventArgs, ScriptErrorInfo)
Collections (arrays, List, Dictionary)CLR types nested inside arrays / dicts
DateTime / TimeSpan (via typed Deserialize)ScriptFunction (fun lambdas)
Script classes (via typed Deserialize)

Deserialization overloads

// 1. Universal returns Dictionary (like Parse) var dict = Json.Deserialize('{"name":"John","age":30}'); print(dict["name"]); // "John" // 2. Typed by class/struct reference var p = Json.Deserialize(Person, '{"name":"Alice","age":30}'); print(p.GetInfo()); // methods and field access // 3. Typed by class/struct name string var p2 = Json.Deserialize("Person", '{"name":"Bob"}'); // 4. Typed by instance (infers type from prototype) var p3 = Json.Deserialize(new Point(0,0), '{"X":10}'); // infers Point // 5. Case-sensitive option the DEFAULT is the interpreter's case flag: C#-strict (like System.Text.Json), // so `x` ≠ `X`; a REPL `.lax` session makes the default tolerant. An explicit argument overrides either way. var p4 = Json.Deserialize(Point, '{"x":10}'); // case-SENSITIVE: 'x' ≠ 'X' → X=0 var p5 = Json.Deserialize(Point, '{"x":10}', false); // case-insensitive: matches 'X'

Parse (universal)

var obj = Json.Parse('{"name":"John","age":30}'); // Dictionary var arr = Json.Parse('[10,20,30]'); // List

Validation & Format

Json.Validate('{"a":1}'); // true Json.Format(json); // pretty-print existing JSON string Json.Minify(json); // strip whitespace

UTF-8 bytes (no string allocation)

var bytes = Json.SerializeToUtf8Bytes(data); // byte[] var obj = Json.Deserialize(bytes); // Dictionary from bytes // Deserialize also accepts byte[] no separate method needed var d = Json.Deserialize(bytes); // universal var p = Json.Deserialize(Person, bytes); // typed from bytes var p2 = Json.Deserialize("Person", bytes); // by name from bytes
Which form is cheaper depends on the work, and assets/language/repl/bench/bench_json_string_vs_bytes.slc measures it on your own machine: one 1.5 MB document written and read both ways, interleaved, every round printed, with the minimum reported, plus what each call ALLOCATES, which is the reading that does not drift. Allocation states the difference plainly: writing to a string allocates two extra copies of the document (the bytes it built, then the string it decoded) and reading from a string allocates one (the encode), while the byte forms build neither. WRITING is otherwise dominated by building the JSON, so the two forms land close to each other in TIME. READING is where the byte form earns its keep. The larger lever is Deserialize against Parse: the typed form also walks the result to rebuild __type objects, which on that document allocates many times the document's own size. Reach for the byte form when reading a big payload, and for Deserialize when the payload has to come back as objects. Deserialize is ONE door, reading a string and a byte[] alike, and both serializers take the same options, read by one reader.

File I/O

Json.ToFile("out.json", data); Json.ToFile("out.json", data, true); // pretty-print var loaded = Json.FromFile("out.json");
// Serialize class with options var p = new Person(); print(Json.Serialize(p)); // {"name":"John","age":30} var opts = new Dictionary<string, object>(); opts["includeType"] = true; print(Json.Serialize(p, opts)); // {"__type":"Person","name":"John","age":30} var opts2 = new Dictionary<string, object>(); opts2["includeNonPublic"] = true; print(Json.Serialize(p, opts2)); // includes private fields // Deserialize 3 ways var d = Json.Deserialize('{"name":"Alice","age":30}'); // Dictionary var c = Json.Deserialize(Person, '{"name":"Alice","age":30}'); // ClassInstance var c2 = Json.Deserialize("Person", '{"name":"Bob"}'); // by type name // Case-sensitive matching (default: true) var p = Json.Deserialize(Point, '{"x":10}'); // 'x' ≠ 'X' X=0 (not set) var p2 = Json.Deserialize(Point, '{"x":10}', false); // case-insensitive: X=10 // Enum serialization enum Color { Red, Green, Blue } print(Json.Serialize(Color)); // {"Red":0,"Green":1,"Blue":2} var col = Json.Deserialize(Color, Json.Serialize(Color)); print(col.Red); // 0 (dictionary key access) // Round-trip: class → flat JSON → typed class var orig = Json.Serialize(c); var restored = Json.Deserialize(Person, orig); print(restored.name); // "Alice" // Nested classes deserialize recursively var co = Json.Deserialize(Company, '{"name":"ACME","addr":{"city":"Paris","zip":75001}}'); print(co.addr.city); // "Paris"

Merge & Select

Json.Merge(dictA, dictB); // deep-merge B into A (A is mutated) Json.Select(dict, "path.to.field"); // dot-path access into nested dicts
Supported types: null, primitives, dictionaries, lists, class instances, struct instances, arrays. A Task is none of them and answers null by design, since it is a handle to running work rather than data: serialize its result, or the inputs and the outcome (see async / await). Cyclic references detected. AOT-safe via Utf8JsonWriter/Utf8JsonReader zero reflection. JSON keys are matched to field names case-insensitively. Missing fields keep type defaults ("", 0, false). If the type name specified in Deserialize is not found, that is an error rather than a fallback a typo must not be mistaken for a deliberate cast. Bytes support: SerializeToUtf8Bytes avoids the string allocation, and Deserialize accepts a string and a byte[] alike, so no separate parse method exists for bytes.

OpenAPI from a JSON sample

Json.ToOpenApi(sample [, options]) answers an OpenAPI 3.0.3 document as text, with its schemas inferred from one example payload, and Json.SchemaOf(sample [, options]) answers that same inferred schema as a dictionary a script can read or edit. The sample is JSON text, UTF-8 bytes, or a value the engine already holds (Json.Parse's answer, a dictionary literal, a class instance: anything Json.Serialize can write). Both members walk one inference, so what SchemaOf shows is what the document embeds.

Json.ToOpenApi('{"id":1,"name":"Ann"}'); // the document, indented Json.ToOpenApi(sample, {"path": "/users", "title": "Users API"}); Json.ToOpenApi(sample, {"extract": true}); // nested objects become components / $ref Json.ToOpenApi(sample, {"method": "post", "side": "request", "status": 201}); Json.SchemaOf('{"id":1}')["properties"]["id"]["format"]; // "int32"
// a captured response, written out as a spec var doc = Json.ToOpenApi(File.ReadAllText("./sample.json"), {"title": "Users API", "version": "1.0.0", "path": "/users"}); File.WriteAllText("./openapi.json", doc);
OptionDefaultWhat it states
titlethe root nameinfo.title
version1.0.0info.version
descriptionabsentinfo.description
path/the path item the operation sits under; a missing leading slash is added
methodgetget, post, put, patch, delete, head, options or trace
rootNamePayloadnames the root schema, and its component when extracting
sideresponseresponse, request or both
status200the response code, 100 to 599
extractfalsenested objects go to components/schemas and are referenced with $ref
formatstruedetect date-time, date and uuid
requirednonesample marks what every merged sample carried
additionalPropertiesabsentstate it explicitly, true or false; absent means the spec's default, which allows them
prettytrueindented output; false is one line

What the sample decides. A boolean is boolean; a whole number is integer with int32, or int64 once a value does not fit; a fractional number is number with double; a string is string, plus a format only when its shape is unambiguous; an object is object with its properties in the order the sample wrote them; an array is array with items merged across every element. Reading one element only would give a wrong spec on real data, so properties are unioned and required: "sample" keeps only what every element carried. Two shapes that disagree collapse to {} (any value), the one honest answer when the data contradicts itself, while integer beside number widens to number. A property that is only ever null states nothing ({}), because a null says nothing about a real value; a null mixed with a value adds nullable: true. A reference carries nullability through allOf, which is the only shape 3.0 allows beside a $ref.

Why the keys are lowercase. OpenAPI's member names (openapi, info, paths, properties, $ref) are the specification's, so this is the one document here that does not use the engine's PascalCase convention, and a schema Json.SchemaOf answers uses the same spelling because it is the same schema. Component names are built from the property name in PascalCase, with a numeric suffix where two would collide, and only the specification's own alphabet is used, so a property called first name still yields a valid name. The order of every group, and of the properties, is fixed and an absent member is omitted, which is what makes two documents from one sample byte-identical.

A single sample cannot state an enum, a minimum or maximum, a pattern, an example, or which fields are optional, which is why required is off by default: a spec that overstates what is mandatory rejects payloads the API accepts. Identical nested shapes are not deduplicated, so two properties with the same structure become two schemas. One call describes one path and one method, and a document that merges several endpoints is the caller's to assemble. SchemaOf always answers the inline schema whatever extract says, because a schema a script holds has no document around it to reference. Only date-time, date and uuid are detected: email and uri are left out because one sample cannot disprove them, and a generator reads format as a promise. The member reads the SAMPLE, never the script's classes: a class and the payload it serializes can disagree, and the payload is what a client sends. Version 3.0.3 is the only dialect written; "openapi": "3.1.0" is a second emitter (3.1 replaces nullable with a type array) and is not accepted yet.

Checking a value against a schema

Json.ValidateAgainst(schema, value) answers whether a value matches a schema, and where it does not. It is Json.SchemaOf's pair: one member answers the schema a sample implies, the other enforces it, so the schema a script holds is the one it can check against. The value is JSON text, UTF-8 bytes, or a value the engine already holds, and a STRING is read as the JSON TEXT (the reading this whole namespace gives one). The answer is a dictionary with ok, the path of the first mismatch in the notation a JSON reader knows, and the message naming it, both empty when the value matches.

var v = Json.ValidateAgainst(Json.SchemaOf(sample), payload); if (!v["ok"]) { print("refused: " + v["message"]); } // refused: $.id: expected an integer // A schema a script STATES is checked too, which is where a rule a sample cannot establish belongs: Json.ValidateAgainst({ "type": "object", "properties": { "a": { "type": "integer" } }, "required": ["a"], "additionalProperties": false }, '{"a":1,"b":2}')["path"]; // $.b (an additional property is not allowed)

What a check covers is what a document can state: type, properties, required, items, nullable and additionalProperties, at any depth, with the path of the first mismatch ($, $.id, $.lines[2].qty). A format is NOT enforced: date-time, date and uuid are shapes a sample's text suggested, and a generator reads them as advice, so refusing a payload for a format the engine merely guessed would reject data the API accepts. A keyword this cannot honour (enum, $ref, oneOf, minimum) is refused by name rather than ignored, because a constraint that is silently dropped is a contract the caller believes it has.

An integer means an integer: a fractional number is refused, even one whose value is whole, and a null is refused unless the schema says nullable. The required list has two sources and they are UNIONED, exactly as the document writes them: what a schema STATES, and what every merged sample carried when the check was asked to enforce that. A route uses this same check on the request it received, which is what makes a published contract one the server keeps.

Extending namespaces

Any namespace (including Json, File, Http, etc.) can be extended with user-defined functions or properties by simple assignment. This works because namespaces are reference types modifications are visible to all importing scripts.

// Add a function to the Json namespace Json.Reverse = (x) => { var chars = [c for c in x]; var result = ""; var i = Count(chars) - 1; while (i >= 0) { result = result + chars[i]; i = i - 1; } return result; }; // Call it like a native method print(Json.Reverse("hello")); // "olleh" // Also works for properties Json.Version = "1.0"; // Re-defining an existing method shows a warning: Json.Serialize = (x) => "overridden!"; // ⚠ Warning: Json.Serialize already exists.
// In an include file (json_utils.inc), import once and use everywhere: // json_utils.inc contents: Json.Pretty = (value) => Json.Serialize(value, true); Json.Get = (obj, path, def) => { /* nested access */ }; Json.Pick = (obj, keys) => { /* filter keys */ }; // Usage: import "../json_utils.inc"; print(Json.Pretty([1, 2, 3]));

Avro schemas and their three encodings are a namespace of their own: see Avro.

Bytecode Compile your functions once, save them to a .slcbc file, and run them later same process or a completely different one

Bytecode lets you save a compiled function to disk and run it later without the original source. Think of it as a tiny "DLL" for ScriptLangCore: your function is compiled to the internal bytecode format, written to a binary .slcbc file, and re-loaded in any later interpreter even a separate process. No parser and no AST are involved: the blob carries only value data (literals + type info) and nested-lambda shells.

Only functions the VM can compile are exportable, which includes a plain value-yield coroutine: its body compiles like any other and the loaded call wraps it so the yield sequence survives. Anything else (a body that falls back to the tree-walker, or a coroutine the VM cannot back, such as one that requests a yield) is skipped and reported (see Limitations).

Quick start 30 seconds

// writer.slc build once, save to disk int sumTo(int n) { var s = 0; for (var i = 1; i <= n; i = i + 1) { s = s + i; } return s; } print(Bytecode.ExportScript("C:/Temp/mylib.slcbc")); // "exported 1, skipped 0" // loader.slc run later, source file not needed Bytecode.LoadScript("C:/Temp/mylib.slcbc"); print(sumTo(10)); // 55 the function exists again, from bytecode

A .slcbc as a program

A bundle is not only a library. --compile writes one without running the script, and the executable runs a bundle the way it runs a .slc file:

ScriptLangCore.exe --compile app.slc // builds app.slcbc, runs nothing ScriptLangCore.exe app.slcbc // runs the program ScriptLangCore.exe app.slcbc --quiet // the CLI switches a .slc accepts work here too

What the bundle carries explains how it runs. Its functions travel as bytecode, and its top level travels as source, so the program starts exactly as the file does. That second half covers the shapes a compiled entry cannot: a top-level const, whose const-ness the interpreter registers at declaration, or a body the compiler declines. The source travels deflated, so a bundle's bytes do not contain the program's text.

--source=strict, which --no-source is shorthand for, leaves the source out entirely. The top level then runs from bytecode, and its declarations, the bundle's classes and structs, travel as descriptors. A program whose top level the compiler cannot compile is refused by name instead of being written. An instance field's initializer travels as a compiled body of its own, so public int V = 5; and public int Doubled = 5 * 2; build the same instances from a bundle as from the file; one that reads the instance (public int W = this.V + 1;) is refused by name, because the body that carries it has no this. A ref/out argument whose target is a top-level variable travels as a cell over that variable, so a swap, an out and a ref at the top level run from a bundle as they do from the file. An interface's default bodies and property accessors travel the same way, and a class carries the interfaces it implements, so x is IBox<int> answers from a bundle as it does from the file. An import travels as its own data (the path, an alias when it has one, and the statement's position), and the loader re-imports the module before the entry runs, so a one-line import no longer costs the whole file its source. An optional parameter's default value travels with its declaration as a compiled body of its own, so a stripped bundle answers F(1) for int F(int a, int b = 3) exactly as the file does. A default that a loaded body cannot answer is refused by name: one that reads the instance (this) or a name the bundle cannot resolve. A top-level const is compiled into the entry and keeps both its value and its const-ness, so a write to it is refused from a stripped bundle exactly as from the file. Without a flag the bundle CARRIES the program text, which is the default and what a plain --compile has always done; --source=strip leaves the text out whenever that is honest and carries it, saying which in the report, when it is not; and --source=strict (what --no-source is shorthand for) leaves it out or refuses the compile by name. So a bundle written with strip or strict always tells you what it is:

ScriptLangCore.exe --compile app.slc --source=strict // no source in the bundle, or a refusal naming why [bc] app.slc -> app.slcbc: exported 1, skipped 0, entry __program__, source stripped, 1 class(es), 0 struct(s) Error: could not write app.slcbc: Bytecode: cannot strip the source: the stripped form cannot carry the initializer of 'K.W' (an instance field's initializer, and its expression reads 'this', which a loaded body has no instance for), so an instance it builds would not hold the value the script gives it. Compile without --no-source, which carries the source and behaves as the script does. ScriptLangCore.exe --compile big.slc --source=strip // strip when honest, carry when not, and say which [bc] big.slc -> big.slcbc: exported 4, skipped 0, entry __program__, source carried instead (the stripped form carries no default value for 'K.M.a' (its expression reads 'this', which a loaded body has no instance for), so a call that omits it would be refused at run time instead of using the default) ScriptLangCore.exe --compile app.slc // the default: the source travels, and the report says nothing about it

What the stripped form carries

Every declaration below, and the verdict each one gets from the strip gate. A refused shape is refused by name, before the bundle is written, because a bundle that silently differed from its script is the one outcome worth an error; --source=strip never refuses, it carries the source instead and says so in the report. So --source=strict, or its --no-source shorthand, is the opt-in that promises the bundle IS the program, and a file it cannot promise that for is still compilable, one flag short.

Declaration--source=strictNotes
the file's top level✅ carriedit becomes the bundle's ENTRY, the synthetic __program__, so the bundle runs the program rather than being a function library
functions, and local functions✅ carriedbytecode bodies. A local function declared INSIDE a block travels too, and a call to it resolves. One declared inside a lambda is the same: that body has no scope dictionary of its own, so the declaration travels in the bundle's function table and the call finds it. One declared inside a plain function travels as its source TEXT instead, which runs that body on the tree exactly as the file does
methods (instance and static), constructors, operators, destructors✅ carriedbytecode bodies, including a bare sibling call inside one
classes and structs✅ carriedas descriptors: fields, properties and the bodies above. A static field's value travels with it
enums, delegates, interfaces, extension blocks✅ carriedthe declaration sections, so the four kinds that have no class or struct descriptor of their own still travel
an interface's DEFAULT body, or a property accessor✅ carriedas member shells, like every other body, so a class that does not implement the member runs the same body from a bundle as from the file. A class also carries the interfaces it IMPLEMENTS, which a generic contract is matched by
import "./mod.inc", bare or with an alias✅ carriedas the statement's own data: the module is re-imported, through the same visitor a source run uses, BEFORE the entry runs, with the bundle's own directory resolving a ./ path. A CONDITIONAL import is not carried (replaying it would make it unconditional), so it declines the top level and the strip refuses by name
a top-level const✅ carriedcompiled into the entry with its const-ness, so a write to it is refused from the bundle exactly as from the file
an optional parameter's default value✅ carrieda compiled zero-parameter body of its own, so F(1) answers for int F(int a, int b = 3) as the file does
an instance field's initializer✅ carriedthe same shape as a default, so public int V = 5; and a computed one build the same instance. One that reads the instance is refused below
a params tail✅ carriedassembled before the call, and the tail does not count towards the required arguments
a generator (yield)✅ when the VM can back ita plain value yield travels and its drive steps it. A body that also makes a REQUEST (sleep, http, an event, ReadLineAsync) is refused below
an async body✅ carriedits await is an opcode, and the async-ness travels with the declaration, so a call from a compiled body hands its caller a Task as the file does
a ref/out argument on a METHOD call (c3.Bad(out v3), Interlocked.Increment(ref counter))✅ carriedthe argument travels as a cell over its target (a local slot, or a global), the callee writes through it, an out is checked on return, and the call site's keyword travels with the call so a swap is still refused by name
a ref/out argument on a FUNCTION call, an OVERLOADED name included✅ carriedthe same cell, and the keyword travels with the call, so the picker chooses the member the keyword fits (Bump(ref n) beside Bump(int, int)) and a call no member can honour is still refused by name, as a flag whose position falls in a params tail is
a top-level statement the compiler cannot model (o is int n, an await, a var lambda that calls itself)✅ carried, as its own SOURCE TEXTthat one statement runs on the tree exactly as in a source run, while the rest of the top level compiles as usual. This is the statement carrier (VmSetStatementCarrier, on by default); SLC_CARRIED_STATEMENTS=0 turns it off, and then a declined statement refuses the file instead. What a carried statement DECLARES (var g = (...) => { ... g ... }) lands in the global scope when it runs, so a later compiled statement calls it normally
every statement of the top level declined, or one with no source text to carry❌ refusedthere would be no entry to run; the message names the statement kind
a class whose instance field has an initializer that reads the instance (public int W = this.V + 1)❌ refusedan initializer travels as a body of its own, which has no this, so the compiled form would read a null instance; the message names the field (Owner.field)
a generic class (class Box<T>)❌ refuseda descriptor does not reproduce it, so an instantiation would be missing at run time
a QUALIFIED interface receiver (IShape.area(x))❌ refuseda script interface is a name with no VALUE, and the VM stops at that instruction; a bundle's body is compiled only, so the run would end part-way. The message names the interface
an out var declaration✅ carried, as its own SOURCE TEXTit names a variable the TREE creates, so a compiled body has no declaration for it: the statement is carried and the variable exists in the bundle exactly as in the file (Give(out var made) then a read of made answers the same from both)
a ref or out argument naming a FIELD, a PROPERTY or an ELEMENT (Fn(ref h.F), Fn(ref a[i]))✅ carriedthe target travels as a cell built by the engine's own resolver (__ref_field__ / __ref_elem__), the same storage a compound assignment writes through, and the call site's keyword travels with it. Only a CHAINED index (a[i][j]) and a range stay on the tree, because the resolver would hand back a copy of a struct element
a REF RETURN (ref int F() { return ref x; })✅ carriedthe body travels as BYTECODE and the header's flags byte says it is a ref return, because the RETURN has to know: it dereferences for a value consumer and hands the cell back to an lvalue use. An lvalue call carries a marker of its own, so a bundle keeps F(..) = 7; and ref int r = ref F(..); working, or box.F() = 7; on a method
a ref LOCAL (ref int r = ref x;, var r = ref h.F, var r = ref a[i])✅ carriedthe target is a global, a FIELD or an ELEMENT, so the local holds the TARGET cell (the VM REPLACES the slot cell rather than nesting two, so the binding is the reference itself). Over a LOCAL variable it is an ALIAS: the two names are ONE storage, so the compiler maps the name to the target slot and emits nothing at all
a want-reference call as an LVALUE in the two shapes the compiler does not compile: a BARE call to the class's own method (Cell() = 12; inside a method), or one that NAMES its argument (box.Cell(add: 0) = 9;)✅ carriedthe BARE form works and the method's body travels as its own text, so the bundle answers what the file answers (that body is walked rather than compiled). The NAMED form is a LANGUAGE limit rather than a bundle one: assigning through a call that names its arguments is refused, with the same message from a file and from a bundle, while READING the same call is fine
an in parameter (int Scale(in int v))✅ carriedits declared TYPE travels with the parameter, which is what a call checks; read-only-ness is a PARSE-time rule, so a body that writes the name never existed and there is nothing to carry
an await foreach (an async stream)✅ carried, as its own SOURCE TEXTthe bytecode VM has no state for an async enumerator, so the STATEMENT stays the tree's: the compiler declines it and the statement carrier (VmSetStatementCarrier) hands it over by its own text, at the top level and inside an async body alike (a body holding one travels as its own text). The bundle of a file with a top-level await foreach prints what the file prints
an await using (an awaited disposal)✅ carried, as its own SOURCE TEXTthe disposal is a CLR ValueTask awaited from inside a statement, which the bytecode VM has no state for, so the statement (or the body holding it) travels as text and runs on the tree as in a source run
an extension property, an extension operator, a generic extension block❌ refusedno descriptor slot for the first two, and a generic block's members are compiled per instantiation, so there is no bytecode to carry
a member whose body the compiler did not take, a CONSTRUCTOR included✅ carried, the class or struct as its own SOURCE TEXTa body the compiler left to the tree (or a coroutine it cannot call from a compiled body) has no bytecode for a descriptor, so the DECLARATION travels as text and the loader re-registers it, members and constructors together. It used to be refused by name; measured, constructor_test is 28 passed from the file AND from its bundle now
the same NAME declared as both a class and a struct✘ refuseda source run resolves names in DECLARATION ORDER, while a bundle registers every declaration before its entry runs, so the later one wins from the first statement and the earlier one's members are unreachable; the message names the name
an optional parameter's default that reads this, or a name a loaded body cannot resolve❌ refuseda default travels as a body of its own, which has no instance; the message names the parameter (Owner.Method.param)
a call to a name the bundle cannot resolve❌ refusedthe call would fail at run time instead of resolving as it does in the file, and the message names what is missing

From a script, Bytecode.ExportProgram(outPath, source [, entryName] [, options]) does the same for a source text you hold, compiling it in a fresh interpreter so your own session is untouched. It strips the source by default, unlike ExportScript, and takes the same { "source": ... } options, so { "source": "carry" } keeps the program text instead.

In the REPL, .loadslcbc loads the functions and registers what the file declares (its classes, structs and extensions) without running the top level, so a loaded function that builds its own class works:

// app.slc: class Box { public int V = 3; public int Twice() { return V * 2; } } // int MakeBox() { var b = new Box(); return b.Twice(); } // in the REPL: .loadslcbc app.slcbc .functions // MakeBox MakeBox(); // 6, with Box registered from the carried source

Keeping a bundle honest

The verifier that runs at LOAD proves a bundle's format: every body's operands, jump targets, table indices and operand-stack balance, the format version, and the opcode fingerprint. It cannot say whether somebody edited the file after it was built, so --compile also SEALS the bundle: a SHA-256 of the whole file lives in the bundle's own header, and every load refuses a file whose bytes no longer match it. One file, nothing to keep in step.

// Error: Bytecode.LoadScript: this bundle does not match the digest it carries: // the file changed after it was built (the digest differs from byte 5 on: it says 6EAFA7D872BD5225..., // the bytes say C9E9969C30CF5F20...). Rebuild it with --compile, or rebuild it from its source; // a bundle with a sidecar (`<name>.slcbc.sha256`) is checked against that too.

What the digest covers, and what it cannot. The 32 bytes sit at offset 12 of the header and are computed over everything else: every body, every table, the carried source, the version and the fingerprint (a field cannot hash itself, so its own bytes count as zeros). A truncated download, a bad copy and a hand-patched body are all caught, which is what an integrity check is for. It is not a signature: the digest lives in the file it describes, so somebody who edits a body and recomputes that field produces a file that passes. For that question keep the expected hash somewhere the artifact cannot reach: Bytecode.WriteBundleManifest(path) writes a sha256sum-compatible sidecar, a sidecar you place beside a bundle is still honoured by every path load, and a mismatch is refused by name.

No sidecar means no second check, which keeps a bundle a script exported into a temp folder working exactly as before, and a blob from an older engine answers its clean version refusal before the digest is even looked at.

A bundle whose sections do not line up says so. A reader and a writer of this format disagreeing about one field is what a broken format change looks like, and a length read from the wrong place used to ask the runtime for that many bytes, so it surfaced as Out of memory on a file of a few hundred bytes. A string whose declared length is past the end of the blob, and bytes left over after the last section, are refused as what they are: the bundle's descriptor stream is out of phase: a string at byte 122 declares 127 byte(s) while 46 remain. The sentence names the position and the counts and says to rebuild with --compile, because a bundle this engine wrote cannot be in that state.

Command line

ScriptLangCore.exe --compile app.slc // writes app.slcbc beside it, runs nothing ScriptLangCore.exe --compile app.slc out.slcbc // writes the bundle where you say ScriptLangCore.exe --compile app.slc --source=strict // ...without the source: bytecode and descriptors only ScriptLangCore.exe app.slcbc // runs the bundle as a program ScriptLangCore.exe --dump-bytecode app.slc // prints what compiled, without running it ScriptLangCore.exe --dump-bytecode app.slc --program // ...and whether the top level itself compiled

--compile always builds, so a second run overwrites the bundle. In the REPL the -bc option is load-or-build instead: it loads the .slcbc sibling when one is there and only builds it when it is not, so a stale sibling is what runs unless you delete it or name another output.

--dump-bytecode prints the constant table, the locals, the global slots and every compiled function of a file, then one summary line per script:

[dump-bytecode] app.slc: 3 compiled function(s), program body: compiled (code=412 globalSlots=9) [dump-bytecode] lib.slc: 2 compiled function(s), program body: declined (while compiling an ExprStmt)

A body the verifier cannot balance is reported as a refusal, and the command fails instead of running it. That is what keeps a corrupted or hand-written bundle away from the executor:

[dump-bytecode] REFUSED __program__: ip 928: POP needs 1 value(s) on the operand stack, but 0 is/are there

A bundle written before the current format version is refused by version, so rebuild it with --compile; a bundle written from a session with no file on disk carries no source, and then the entry recorded at export is what runs. A bundle the engine cannot read at all (another version, a truncated or foreign file) is refused with ONE line that names the version it found and the fix, and a REPL session keeps running: the file counts as a file, the next statement still runs, and the CLR stack trace is printed only when SLC_STACK_TRACE=1 asks for it.

The REPL commands

.run app.slc // run one file .run app.slc -bc // load app.slcbc if it is there, else run the source and build it .run app.slc -bc app.v2.slcbc // the same, writing the bundle where you say .run app.slcbc // run the bundle: its carried source is the program .run stress_*.slc // a glob, or .run a.slc|b.slc for a list of files .run app.slc -q // quiet: the program's own output is suppressed .looprun 50 app.slc // 50 runs of one file; it takes -bc like .run does .loadslcbc lib.slcbc Lib // a library bundle: its functions arrive as namespace Lib .loadslcbc app.slcbc // a program bundle: its functions arrive flat, by name .functions // what is loaded now, with each function's signature

.run accepts several files at once, separated by | or matched by a glob, and each file's Check verdict is its own, so running one twice in a session reports each run separately.

Bytecode.ExportScript(path [, entryName] [, options])

string Bytecode.ExportScript(string path [, string entryName] [, options])

Writes every VM-compiled top-level function of the current script into path as a single-script bundle. Returns an "exported N, skipped M (names)" report so you can see what was saved and what was not. The optional entryName pins which function the bundle declares as its entry (the one LoadScript returns).

Where the program text goes: by default the bundle carries the script's own text, so a bundle whose top level the compiler declined still runs the file it came from. { "source": "strip" } leaves the text out when the strip is honest, and carries it (the report saying source carried instead (...)) when it is not. { "source": "strict" } refuses rather than carrying, naming what could not be stripped, which is what the CLI's --no-source does. An unknown key or spelling is an error, never a silently ignored option.

// the same export, three source modes Bytecode.ExportScript("C:/Temp/s1.slcbc"); // carries the program text Bytecode.ExportScript("C:/Temp/s2.slcbc", { "source": "strip" }); // strips when honest, carries otherwise Bytecode.ExportScript("C:/Temp/s3.slcbc", { "source": "strict" }); // strips, or refuses // the options dictionary also fits the entryName slot, so no placeholder null is needed: Bytecode.ExportScript("C:/Temp/s4.slcbc", { "source": "strict" });

Basic use export, then load in the same process:

// same-process round trip: export the current script's functions, load them back int myMath(int n) { var sum = 0; var i = 0; while (i < n) { sum = sum + i * 3; i = i + 1; } return sum; } print(Bytecode.ExportScript("C:/Temp/myMath.slcbc")); // "exported 1, skipped 0" Bytecode.LoadScript("C:/Temp/myMath.slcbc"); print(myMath(10)); // 135 same result as before the round trip print(myMath(100)); // 14850 loops are part of the bytecode

Advanced use cross-process: write in one run, load in another:

// writer.slc process #1 exports the bundle int myMath(int n) { /* ... as above ... */ } Bytecode.ExportScript("C:/Temp/myMath.slcbc", "myMath");
// loader.slc process #2 (days later, myMath source deleted) var entry = Bytecode.LoadScript("C:/Temp/myMath.slcbc"); // returns the entry function print(entry(10)); // 135 executed from bytecode, no parser involved print(myMath(10)); // 135 every bundle function is also defined by name

Edge cases:

// 1) entryName must be an exported function, else ExportScript throws try { Bytecode.ExportScript("C:/Temp/x.slcbc", "noSuchFn"); } catch (var ex) { print(ex.Message); } // Bytecode.ExportScript: entry function 'noSuchFn' is not VM-compiled or not found in this script. // 2) a value-yield coroutine exports like any other function int countTo(int max) { var i = 0; while (i < max) { yield i; i = i + 1; } return -1; } print(Bytecode.ExportScript("C:/Temp/y.slcbc")); // "exported 2, skipped 0, entry __program__" (countTo and the top level) // 3) a single-script bundle has NO metadata import "x.slcbc" as Z will not work for it. // Use LoadScript for single-script bundles; import needs a library (ExportLibrary).
A value-yield coroutine IS exported, and the loaded call wraps it so the yield sequence survives. What stays out is a coroutine the VM cannot back from a compiled call, one that REQUESTS a yield (sleep/HTTP/event): it is skipped and named in the report.

In-memory bundles: the ...Bytes forms

Every member that reads or writes a .slcbc file also has a form that takes or returns byte[]. Use them when a bundle should not touch the disk: a blob in a database column, bytes from a socket, or a test that builds a library in memory. The file form is the memory form plus one read or one write, so the two cannot disagree about what a bundle is. A library's inputs need no files either, and the two forms differ in what a spec's string means: ExportLibrary reads it as a path, while ExportLibraryBytes reads it as the script text, so no Encoding call is needed for a script you hold. A byte[] spec is the script's text in both, and the member decides, so nothing is guessed from the value.

BytecodeResult Bytecode.ExportScriptBytes([string entryName] [, options])
BytecodeResult Bytecode.ExportProgramBytes(string source [, string entryName] [, options])
BytecodeResult Bytecode.ExportLibraryBytes(meta, scriptOrTuple... [, string[] ignoreVars])
BytecodeResult Bytecode.MergeLibraryBytes(meta, libOrBytes...)
Namespace Bytecode.LoadNamespace(byte[] bytes [, string alias])
Function Bytecode.LoadScript(string|byte[] pathOrBytes)  ·  string Bytecode.GetSource(string|byte[] pathOrBytes)  ·  string Bytecode.MergeLibrary(string outPath, meta, libOrBytes...)

The exporters return a result value with two members: .Bytes (the blob) and .Report, the same report string the file form returns, which is where skipped names and a carried source are named. A { "source": ... } dictionary means the same here as it does for the file form.

LoadNamespace(bytes [, alias]) is the memory form of import "x.slcbc" as Z. It returns the library as a namespace value, because import takes its path in the syntax. The alias is the label the library is reached by: it names the namespace being returned, and that label is a path segment through the value, so Z.What.A.add(2, 3) works beside Z.A.add(2, 3). It is deliberately NOT a name in scope: What.A.add(...) is undefined, because the path starts at the value you already hold. With no alias there is no label to spell, and the value is simply the namespace. Assign it and call through it like any namespace, and a merge may mix the two spellings, so a library on disk can join ones in memory.

Composition nests: a merged blob can be merged again, and a library's own function may call MergeLibraryBytes and hand the result back, so one library can know how to combine others. The only rule is that a function name stays unique across everything being merged, in its namespace, or the merge is refused and names the collision. There is no limit on how many libraries one call takes.

// two scripts to one namespaced library, nothing written to disk var meta = Bytecode.Meta("pair", "1.0"); var a = Bytecode.ExportLibraryBytes(meta, ("int add(int x, int y) { return x + y; }\n", "A")); // the script TEXT, no file var b = Bytecode.ExportLibraryBytes(meta, ("int mul(int x, int y) { return x * y; }\n", "B")); print(a.Report); // "exported 2, skipped 0" var one = Bytecode.MergeLibraryBytes(meta, a.Bytes, b.Bytes); // "merged 4" var Z = Bytecode.LoadNamespace(one.Bytes, "Z"); print(Z); // "Z" the alias names it print(Z.A.add(2, 3)); // 5 the namespaces survive the merge print(Z.Z.A.add(2, 3)); // 5 the label is also a segment through the value var prog = Bytecode.ExportProgramBytes("print(\"hi\");", { "source": "carry" }); print(Bytecode.GetSource(prog.Bytes)); // the text those bytes carry

Bytecode.LoadScript(pathOrBytes)

Function Bytecode.LoadScript(string|byte[] pathOrBytes)

Reads a single-script bundle, defines every function into the current interpreter's global scope, and returns the entry function (or null when the bundle declared none). Every function body is decoded and verified at load, so a body that does not verify refuses the load here, naming the function, instead of failing when something first calls it.

Basic use load and call by name:

var entry = Bytecode.LoadScript("C:/Temp/lib.slcbc"); print(entry(10)); // 55 the returned entry function print(sumTo(10)); // 55 same function, also bound by name in global scope print(myMath(10)); // 135 non-entry bundle functions are defined too

Advanced use the entry as a "main": combine entryName at export time with the returned value at load time to give a bundle a clear entry point:

Bytecode.ExportScript("C:/Temp/lib.slcbc", "sumTo"); // pin the entry var main = Bytecode.LoadScript("C:/Temp/lib.slcbc"); print(main(10)); // 55 main is sumTo print(typeof(main)); // "Function" it is a normal callable

Edge cases:

// a bundle with no functions returns null var nothing = Bytecode.LoadScript("C:/Temp/empty.slcbc"); print(nothing == null); // True // loaded shells are VM-only: no tree-walker fallback exists for them (they carry no AST). // If the environment is incompatible the error surfaces AT CALL TIME see Limitations.

Bytecode.ExportLibrary(outPath, meta, scripts... [, ignoreVars])

string Bytecode.ExportLibrary(string outPath, meta, scriptOrTuple... [, string[] ignoreVars])

In memory: Bytecode.ExportLibraryBytes(meta, scripts... [, ignoreVars]) is this member without the output path, returning a result value to read .Bytes and .Report from (see In-memory bundles under Bytecode.ExportScript). Each script is written as a (script, ns) tuple or a bare script. Here a spec's string is a path (use ExportLibraryBytes to give the script TEXT instead), and a byte[] spec is the script's text, which is what makes a library buildable with nothing on disk.

Builds a library from several scripts into one .slcbc file. Each argument is either a script path (its functions land flat) or a (script, namespace) tuple (its functions land under namespace.*). A library also snapshots the modules' classes, structs, and top-level variables. Libraries carry metadata, so they can be loaded with import "lib.slcbc" as Z and expose Z.__meta.

An exported function keeps its optional parameter defaults, so Z.add(2) answers for int add(int x, int y = 3) just as the script does. A default that the library cannot carry is refused at export, naming the parameter: one that reads the instance (this), reads a name the library cannot resolve, or reads a top-level variable (a library's variables are snapshots, not bare names, so a function body cannot read one either).

meta is a Bytecode.Meta(name, version, description) value or a dict { "name": ..., "version": ..., "description": ... } both accepted.

Basic use one script, import as a namespace:

// build.slc merge one script into a library var meta = Bytecode.Meta("TestLib", "1.0", "my library"); print(Bytecode.ExportLibrary("lib.slcbc", meta, "math.slc")); // "exported 3, skipped 0"
// user.slc any later process import "lib.slcbc" as Z; print(Z.add(2, 3)); // 5 flat functions live directly on Z print(Z.__meta.Name); // TestLib the metadata round-trips

Advanced use namespaces, variables, and classes:

// a.slc has add/mul; b.slc has greet and a top-level var var meta = Bytecode.Meta("TestLib", "1.0", "two-module lib"); print(Bytecode.ExportLibrary("lib.slcbc", meta, ("a.slc", "Math"), // a.slc's functions land under Math.* "b.slc")); // b.slc's land flat
import "lib.slcbc" as Z; print(Z.Math.add(2, 3)); // 5 a.slc's add at Z.Math.add print(Z.Math.mul(6, 7)); // 42 print(Z.greet("bob")); // Hello bob flat print(Z.LIB_CONST); // 42 top-level variable snapshots travel too var g = Z.sumTo; print(g(5)); // 15 namespace members are usable as values

Edge cases the strict variable contract and the ignoreVars escape hatch:

// STRICT default: an unserializable top-level variable ABORTS the export and // NO file is written a partial library would silently lose state. try { Bytecode.ExportLibrary("bad.slcbc", meta, "module_with_proc.slc"); } catch (var ex) { print(ex.Message); } // Bytecode.ExportLibrary: variable 'proc' is not serializable (value of type ProcessHandle // cannot be serialized). Remove or make it serializable before exporting the export is // aborted and no file is written. // ESCAPE HATCH: list the name in a trailing array those variables are skipped with a warning print(Bytecode.ExportLibrary("ok.slcbc", meta, "module_with_proc.slc", ["proc"])); // [WARNING] Bytecode.ExportLibrary: variable 'proc' is in ignoreVars skipped (not exported). // "exported 1, skipped 0" // duplicate function names across modules abort the export try { Bytecode.ExportLibrary("dup.slcbc", meta, "a.slc", "a.slc"); } catch (var ex2) { print(ex2.Message); } // duplicate function 'add'.
import requires an alias: import "lib.slcbc" as Z a bare import "lib.slcbc" is an error for bytecode libraries. And a library is required: single-script bundles (ExportScript) have no metadata and cannot be imported this way use Bytecode.LoadScript for those.

Bytecode.MergeLibrary(outPath, meta, libPaths...)

string Bytecode.MergeLibrary(string outPath, meta, string libPath1 [, string libPath2...])

Merges already-compiled .slcbc libraries into one file. The per-module namespaces are preserved, and the caller-supplied meta becomes the merged library's __meta. Returns "merged N". Each input may also be the library's byte[] rather than a path, so a merge can combine a library on disk with ones in memory, and Bytecode.MergeLibraryBytes(meta, libs...) takes and returns bytes with no file involved at all.

Basic use combine two libraries:

print(Bytecode.MergeLibrary("merged.slcbc", { "name": "Merged", "version": "1.0" }, "libA.slcbc", "libB.slcbc")); // "merged 7"
// import the merged library namespaces survive the merge import "merged.slcbc" as M; print(M.Math.add(2, 3)); // 5 libA's Math namespace print(M.greet("x")); // Hello x libB's flat function print(M.__meta.Name); // Merged the caller-supplied meta

Edge cases:

// inputs must be libraries, not scripts MergeLibrary reads .slcbc files // duplicate function names (same namespace + name in two libs) abort the merge try { Bytecode.MergeLibrary("m.slcbc", meta, "libA.slcbc", "libA.slcbc"); } catch (var ex) { print(ex.Message); } // duplicate function 'add'.

Bytecode.GetSource(pathOrBytes)

string Bytecode.GetSource(string|byte[] pathOrBytes)

Returns the program text a bundle carries, as a string, with the engine doing the unpacking. A whole-script bundle carries its top level, so this is the source the bundle was built from; a library bundle carries no program of its own and answers "". Use it to read what a bundle holds, or to keep a bundle's source without keeping the original file beside it.

Inside the file, that text is stored compressed, which is why a bundle's bytes no longer contain it in the clear. That is an implementation detail of the format rather than something a caller has to undo. A file that is not a bundle is refused by name: Bytecode.GetSource: not a ScriptLangCore bytecode bundle.

var text = Bytecode.GetSource("app.slcbc"); print(text.Length); // the program's size in characters print(Bytecode.GetSource("lib.slcbc")); // a library: empty

Bytecode.Meta(name [, version, description])

Meta Bytecode.Meta(string name [, string version, string description])

Creates the metadata value used by ExportLibrary / MergeLibrary and returned by imports as Z.__meta. A plain dict { "name": ..., "version": ..., "description": ... } is accepted anywhere a Meta is expected.

Basic use:

var meta = Bytecode.Meta("TestLib", "1.0", "two-module lib"); print(typeof(meta)); // Meta print(meta is Meta); // True Bytecode.ExportLibrary("lib.slcbc", meta, "math.slc");

Advanced use the dict form, and reading it back on import:

// dict form is equivalent var meta2 = { "name": "TestLib", "version": "1.0", "description": "hi" }; Bytecode.ExportLibrary("lib.slcbc", meta2, "math.slc"); // on import, Z.__meta exposes the fields import "lib.slcbc" as Z; print(Z.__meta.Name); // TestLib print(Z.__meta.Version); // 1.0 print(Z.__meta.Description); // hi

Edge cases: a "entry" key in a dict is intentionally ignored (metadata is informational). After an export/merge, __meta.Sources lists each function's namespace ("" = flat) useful for diagnostics.

REPL commands

.export -bc <file.slc> [out.slcbc] [ns] runs a script and exports its VM-compiled top-level functions to a bytecode LIBRARY (it carries no source, so a source flag is refused there); .export -bundle <file.slc> [out.slcbc] [--source=carry|strip|strict] writes a PROGRAM bundle instead and runs nothing, with the same flags as the CLI; .loadslcbc <file.slcbc> [alias] loads a bundle a library becomes a namespace under the alias (default: file stem), a single-script bundle loads flat; .run, .looprun and .bench accept -bc [out.slcbc] and .run loads a .slcbc path directly.

Limitations what is NOT supported yet

  • Only VM-compiled functions can be exported. Functions whose body falls back to the tree-walker have no bytecode and are skipped at export (reported in the "exported N, skipped M" report): coroutines (yield) their bytecode is only valid when driven through the in-process generator/coroutine VM machinery (VmSuspendState); an exported bundle calls bodies plain and would run them eagerly, losing the yield sequence, so they are still skipped at export and any body containing a construct the VM does not yet compile (unknown shapes). The VM does compile ref/out params, self-recursive functions (with VM tail calls), bare-name method calls inside class/struct methods (self-recursion, sibling methods resolve through the class context), try/catch/finally, foreach, switch statements and expressions (constant, type, var, discard patterns, when guards, multiple labels), new, ternary/??, prefix and postfix ++/-- on locals, globals, and property/index targets, compound assignment (+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=) on locals, globals, and property/index targets, named arguments (f(x: 1) the VM reorders them against the callee's parameter list), using bodies that return/break/continue, const declarations (reassignment throws), and lambdas with capture-free, read-only local, or global captures (write-capturing lambdas fall back to the tree); local functions are compiled to bytecode with VM captures too.
  • Whole-script bundles. ExportScript exports all VM-compiled top-level functions into one bundle; classes, structs, enums, delegates, and globals are not serialized a bundle only loads where those are already defined. (Libraries built with ExportLibrary do carry classes, structs and top-level variable snapshots.)
  • Environment-coupled. A bundle that references a script class/struct/delegate/global only runs in an environment that defines them. The mismatch is caught at call time with a clear error referenced types and globals must exist when the loaded function runs.
  • No tree fallback for loaded shells. A loaded function is VM-only: if the VM cannot execute it at call time (e.g. an unsupported construct slipped through), it raises an error instead of silently tree-walking loaded shells have no AST body.
  • Compiler-coupled. The blob format is pinned to a deterministic opcode fingerprint; the bundle version number is deliberately kept stable at 1 (on-disk layout changes are documented in code, not by bumping the number). Bytecode written by a different ScriptLangCore build is rejected on fingerprint mismatch, not migrated there is no cross-version compatibility layer.
  • Binary format. Blobs are opaque binary files (.slcbc); there is no textual/disassembly export and no safe way to hand-edit them.
  • Nested lambdas are shell-only. Lambdas inside an exported function are serialized as parameter/return-type shells plus bytecode their captured state is rebuilt at runtime, so they must be capturable by the VM (capture-free, read-only local, and global captures work; lambdas that write a captured local fall back to the tree).
VmXXX bytecode VM control Inspect & control the bytecode VM VmStats, VmSetEnabled, VmSetTopLevelEnabled, VmSetStatementCarrier, VmReset, VmSetTrace

ScriptLangCore executes functions through an internal bytecode VM (compiled at parse time from the AST) with a silent fallback to the tree-walker for constructs the VM does not yet compile. These built-ins let a script inspect and control that behavior useful for diagnostics, A/B benchmarks, and tracing.

VmStats()

Returns a string reporting how many function invocations ran in the VM vs. the tree-walker since the last reset, e.g. "VM: 26 (92.9%) | Tree: 2 (7.1%) | Total: 28 | cacheHits: 0 misses: 0 | gfast: 100011/100007". The trailing gfast: N/M counts global fast-path accesses LOAD_GLOBAL_FAST / STORE_GLOBAL_FAST operations executed. When a function reads/writes globals in a hot loop, N and M grow large, proving the global slot cache is in use (it skips a per-access dictionary lookup). A trailing toplevel: N counts the top-level statements this run executed on the VM (see VmSetTopLevelEnabled below); it is part of the short form too, because a script whose work is all at file scope reports VM: 0 (no function invocations yet) while statements are running on the VM.

var stats = VmStats(); print(stats);

VmSetEnabled(bool)

Globally enables or disables the bytecode VM. With VmSetEnabled(false) every function runs through the tree-walker (the VM is bypassed entirely) use it for A/B comparisons of the same workload under VM vs. tree. The switch reaches the calls a running compiled body makes after it too, not only the ones the top level makes, so a function that turns the VM off hands its own callees to the tree. One boundary worth knowing: a body loaded from a bundle has no syntax tree to walk, so it keeps running on the VM whatever the flag says.

VmSetEnabled(false); // force tree-walker VmSetEnabled(true); // re-enable VM
Recursion depth limits (runaway guard): a runaway recursion throws a catchable ScriptException Maximum call depth exceeded (N) possible runaway recursion. it never crashes the process, and the guard is silent (no console warning). The limit N depends on the execution path and the build:
  • VM enabled (default): N = 1000000 under NativeAOT, 30000 in Debug/JIT. The VM runs calls on a flat heap frame list the C# stack never grows (measured 100% VM-flat at 1,000,000 levels), so the cap is bounded by memory, not the thread stack: ~370 MB of working set per million levels (the process OOMs catchably at ~20.3M levels).
  • VM disabled (tree-walker): N = 3000 under NativeAOT, 24 in Debug/JIT. The tree-walker recurses on the native C# stack and .NET exception dispatch costs ~3× the recursion's own stack per level, so the guard fires well below the physical limit (~15800 AOT levels) to leave headroom for the guard's own throw to unwind.
Tail-recursive calls are optimized into a loop and run in constant stack, bounded only by the 1000000-iteration tail-loop guard (tailRec(100000, 0) passes). The guard counts every tail call the same invocation makes, so its boundary is a property of the emitted stream rather than of the recursion's depth: pin it with SLC_VM_MAXFRAMES when a specific boundary is wanted. Diagnostic override: the environment variable SLC_VM_MAXFRAMES=N replaces the VM frame cap in both builds.

VmSetTopLevelEnabled([bool])

Runs top-level statements (the code outside every function) on the bytecode VM instead of the tree-walker. Called with no argument it reports the current state; called with one it sets it and answers what it set, so a script can turn it on, compare the two engines, and turn it off again in the same run. Function bodies are unaffected: VmSetEnabled governs those. Statements already executed keep the engine they ran on, so a switch made here applies to the statements after it.

On by default, and the reason to know before changing it: a top-level statement the VM cannot finish is refused rather than re-run, because by then it may already have stored a global and running it again on the tree would repeat that work. Turning it off is for comparing the two engines, or for a session that wants the tree-walker: SLC_TOPLEVEL_VM=0 in the environment does it for a whole run, and VmSetTopLevelEnabled(false) for the statements after the call.

VmSetTopLevelEnabled(true); // the top level runs on the VM (the default) VmSetTopLevelEnabled(false); // ...and on the tree-walker (this run only; SLC_TOPLEVEL_VM=0 does it for every run) print(VmSetTopLevelEnabled()); // read the state: false or true
// The `toplevel:` field of VmStats() is what shows the switch working VmSetTopLevelEnabled(true); VmReset(); var total = 0; for (var i = 0; i < 3; i = i + 1) { total = total + i; } print(VmStats()); // ends with `toplevel: N`, the statements that ran on the VM VmSetTopLevelEnabled(false);

VmSetStatementCarrier([bool])

Controls the statement carrier, a compile-time mechanism: when a program body cannot be compiled as one unit, each top-level statement the compiler cannot model is handed to the tree-walker by its own source text instead, so a file stops having to carry its whole source in a bundle. Called with no argument it reports the current state; called with one it sets it and answers what it set.

On by default since 2026-10-21: it takes --source=strict from 471 stripped of 514 suites to 501 (43 refusals down to 13), and every suite it newly strips has been measured against its own source by src/build/bundle-parity.sh, which is why the eleven bundle defects that gated the flip are closed rather than reasoned (a generic call naming its type parameters, a generic body resolving its own T, an out _ discard, a tuple name in a generic position, an async Task<int> that falls off, a carried statement writing the global where the body reads a local slot, two capture-free lambdas at the same position in two snippets). It governs the compile (the bundle a script exports after the call), not the engine a statement runs on, and the carrying itself is decided per statement, so a file whose top level compiles as one unit is unaffected.

Pass false to compare the two states in one process, and SLC_CARRIED_STATEMENTS=0 to do it for a whole run; the compiler then REFUSES a file whose top level it cannot model, as it did before the flip. The env-var-only era is why the switch exists: Process.Start takes no environment, so before it no suite could reach the carrier. assets/language/repl/run/statement_carrier_test.slc pins it, through a strict Bytecode.ExportProgramBytes compile.
VmSetStatementCarrier(false); // the opt-out: refuse such a file instead of carrying print(VmSetStatementCarrier()); // read the state: true or false VmSetStatementCarrier(true); // back to the default

VmReset()

Zeroes the VM/tree invocation counters so a subsequent VmStats() reflects only the work since the reset. The top-level statement count is zeroed with them.

VmReset();

VmSetTrace(bool)

Enables per-opcode execution tracing. Every VM instruction prints a line to the console: [vm] fn=<name>[depth] [Lx:Cx] ip=N OP sp=N ; decode (e.g. [vm] fn=Inner[1] [L1:C20] ip=7 LOAD_CONST sp=1 ; push const 2). A one-time --- source: file.slc --- banner is printed when the executed source file changes (import boundaries). The tree-walker prints matching [tree] lines. Use VmSetTrace(false) to stop.

VmSetTrace(true); // start tracing // ... run your code ... VmSetTrace(false); // stop
See also the REPL .vm command, which exposes the same controls interactively. The Bytecode entry documents export/load of VM-compiled functions.
Http HTTP client and form decoding GET, POST, PUT, DELETE, timeout, forms

Blocking HTTP requests. In coroutines, yields an HttpRequest for non-blocking dispatch. Returns the response body as a string.

All methods accept an optional timeoutMs parameter (default 30 000 ms).

Forms. Http.DecodeForm(text) decodes one application/x-www-form-urlencoded component: a + is a space and %XX is one byte, so a multi-byte character survives ("caf%C3%A9" is café), and an escape that does not introduce two hex digits is left as it stands rather than refused. Http.EncodeForm(text) is the inverse, a space written +. Http.ParseForm(body) decodes a whole body into a dictionary, one entry per field: a repeated field keeps its last value and a pair with an empty key is ignored. Test a field with ContainsKey before reading it, because reading an absent key is refused.

// the two lines a form handler needs, instead of splitting on "&" and "%" by hand var f = Http.ParseForm(ctx.Body); var text = f.ContainsKey("text") ? "" + f["text"] : "";

Cancellation. Every verb also accepts an optional CancellationToken, recognised by its runtime type (anywhere after the URL) or with the named form token:. With no token the call binds to the ambient token, readable as Http.Token (read-only): the current host request's token inside the MCP HTTP server, otherwise a process token fired by Ctrl+C, abort() or shutdown. Link your own deadline with the short form CancellationToken.Create(a, b, ...) (returns the token; the engine owns the linked source).

// explicit token cancel a group of calls from one source var cts = new CancellationTokenSource(); var body1 = Http.Get("https://api.example.com/a", 5000, cts.Token); var body2 = Http.Get("https://api.example.com/b", token: cts.Token); cts.Cancel(); // in-flight calls abort // link the ambient token with your own: whichever fires first wins var mine = new CancellationTokenSource(800); // 800 ms deadline var t = CancellationToken.Create(Http.Token, mine.Token); Http.Post("https://api.example.com/data", '{"k":1}', t); // tell cancellation from a timeout without string matching if (Http.LastErrorKind == "cancelled") { print("aborted by caller"); }

Failure values. Failures are returned (not thrown) as __HTTP_ERROR__:<message>. Two causes are named explicitly: __HTTP_ERROR__:cancelled (the ambient or an explicit token fired) and __HTTP_ERROR__:timeout (the per-call timeout fired). Http.LastErrorKind holds "cancelled", "timeout" or "network" for the most recent call, and "" after a success. The two Async members below THROW instead, because a byte count and a byte array have no sentinel slot: their refusal arrives as a catch-able error carrying the engine's own wording, and Http.LastErrorKind is set the same way.

Server-side note. Inside the MCP HTTP server each request gets its own token, exposed to http.Use middleware as ctx.RequestAborted, and cancelled when the server stops or a socket failure is detected. Because HttpListener provides no Kestrel-style abort event, that detection is best-effort: a client that disconnects mid-handler is noticed when the engine next touches the socket. Pass an explicit token or a short timeoutMs when a hard deadline matters.

Http.Get("https://api.example.com/data"); Http.Get("https://api.example.com/data", 5000); // 5s timeout Http.Post("https://api.example.com/data", '{"key":"val"}'); Http.Post("https://api.example.com/data", '{"key":"val"}', 3000); // 3s timeout Http.Put("https://api.example.com/data/1", '{"key":"val2"}'); Http.Delete("https://api.example.com/data/1"); // the BYTES doors: a binary body, and a download that never passes through a string var png = await Http.GetBytesAsync("https://example.com/logo.png"); var written = await Http.DownloadAsync("https://example.com/big.zip", "./big.zip"); print(png.Length + " bytes read, " + written + " written");
MemberDescription
GetBytesAsync(url [, timeoutMs] [, token])The response body as a byte[], read INCREMENTALLY (ResponseHeadersRead, so the body is never buffered whole before it is handed over). Use it for anything binary: Http.Get decodes a body as text, which is wrong twice over for a PNG. It answers the engine's Task, so await it, and the Async postfix is the repository's naming rule for a member that really is asynchronous.
DownloadAsync(url, path [, timeoutMs] [, token])The same transfer written straight to a FILE, answering the byte count, so a large download never becomes a script string. The path follows the one path rule (./x is beside the run), the copy runs chunk by chunk and asks the token per chunk, so a cancellation stops the transfer rather than only its start, and a ./ path needs a run directory (a bare or absolute path needs none).
var resp = Http.Get("https://httpbin.org/get"); print(resp); // raw JSON response // With timeout (100ms will time out on slow/unreachable hosts) try { var data = Http.Get("https://192.0.2.1/test", 100); // unroutable IP } catch (var ex) { print("Timeout: " + ex.Message); // "__HTTP_ERROR__:..." } // In a coroutine non-blocking with timeout var coResp = yield Http.Get("https://api.example.com", 5000);
Timeout behavior: The timeout parameter applies a CancellationTokenSource to the underlying HttpClient call. In synchronous mode, the current thread blocks for at most timeoutMs. In coroutine mode, the background Task.Run is cancelled after timeoutMs, and the scheduler resumes the coroutine with an error result. Default: 30 000 ms (30 seconds).
MCI Media Control Interface audio playback

Play, pause, seek, and control audio files via the Windows Media Control Interface.

MCI.Open("song.mp3"); MCI.Play("song.mp3"); MCI.Pause("song.mp3"); MCI.Close("song.mp3"); MCI.Status("song.mp3"); MCI.Seek("song.mp3", 5000); // seek to 5s
MCI.Open("background.mp3"); MCI.Play("background.mp3"); sleep(10000); // play for 10 seconds MCI.Pause("background.mp3"); MCI.Close("background.mp3");
Bridge One request document in and one response document out, in BOTH directions: a script serves verbs to its host, and calls the host's verbs

A script that does real work usually has a program around it, and the two sides need to talk: the host asks the script to post an invoice, the script asks the host for the customer record. Neither side can hand the other an object, because the two runtimes are separate (a host in C has no script dictionary, and the engine cannot see a C struct). What crosses every boundary is UTF-8 text, so Bridge is ONE document shape used in both directions, and the object graph stays where it lives.

// script -> host: the host's answer, already parsed var answer = Bridge.Call('{"v":1,"id":"7","m":"customer.lookup","p":{"id":42}}'); // host -> script: the handler below answers it Bridge.Serve(fun (req) { if (req["m"] == "invoice.post") { return Bridge.Ok(req["id"], { "posted": true }); } return Bridge.Fail(req["id"], "NoSuchVerb", "no " + req["m"]); });

The document

A request is an object with four members, and only v and m are required:

MemberTypeMeaning
vnumberThe contract version, 1 today. A request naming another version is refused as UnsupportedVersion instead of being mis-read, which is what the number is for.
idanyThe caller's correlation id, echoed verbatim (a string stays a string, a number stays a number), including an explicit null. Absent stays absent rather than being invented. It is how a host matches an answer to its request in a log; no carrier allows two requests outstanding at once, so pipelining would need a batch, which this version does not define.
mstringThe verb, a dotted name such as invoice.post. m is ADDITIVE: adding a verb is not a version change, while removing or re-meaning one is.
pobject or absentThe parameters. An object rather than a value, because a contract that allows one huge value invites a payload no reader can bound; anything large is paged inside it. An explicit null means the same as absent.

An answer is an object too, with v and a boolean ok, then either r (the result, any value) or e (the error object):

{ "v": 1, "id": "7", "ok": true, "r": any } { "v": 1, "id": "7", "ok": false, "e": { "code": "...", "message": "...", "retry": false, "origin": "engine", "retryAfter": 250, "details": { ... }, "at": { "file": "...", "line": 12, "col": 5 }, "frames": ["Post [L10:C9]"] } }

The nine members

A full showcase ships as a script: assets/language/repl/interop/bridge_members_demo.slc uses each of the nine members once, prints the answer that member gave, and asserts it, so the same file is the tour and a pin. Run it with ScriptLangCore.exe assets/language/repl/interop/bridge_members_demo.slc.
MemberWhat it does
Bridge.VersionThe contract version this build speaks, as a number (1).
Bridge.ServedWhether a handler is registered, so a script can decide before it advertises anything.
Bridge.HostedWhether a host installed its side, which is what Bridge.Call needs.
Bridge.Serve(handler)Registers the function that answers the host's requests, taking one parameter (the request as a script dictionary) and answering the text Bridge.Ok or Bridge.Fail builds. Bridge.Serve(null) stops serving. One handler per session, so a second call replaces the first.
Bridge.Handle(request)The host to script door, as text in and text out. This is what slc_invoke and the COM server's Invoke member call, and also what a test drives, so the contract is provable with a stub host and no host technology at all.
Bridge.Call(request)The script to host door. Answers the host's response document already parsed, so a member is read as answer["r"]["n"]. Refuses by name when no host installed its side.
Bridge.Ok(id [, result])The success answer: ok: true with result as r. Omitting result answers a document with no r at all, and the id it takes is not trusted, because the dispatcher echoes the request's own.
Bridge.Fail(id, code, message [, retry | options])The failure answer: ok: false with the contract's error object. code is the non-empty, machine-readable name a client branches on, message is the non-empty text a human reads, and retry: true says the same request may be sent again. The fourth argument is either that boolean or an options object: { retry: true, retryAfter: 250, details: { field: "total" } }. An unknown option, or one of the wrong type, is refused by name.
Bridge.FromError(id, error)The failure answer built from a CAUGHT value instead of invented text: an ErrorInfo, or a { code: ..., message: ... } dictionary, becomes the same error object, so a failure the script handled reads like one the engine caught. A dictionary is read member by member: retry, retryAfter and details travel when present, and a malformed member is refused by name. A caught value carries no position, which is why at is left out rather than guessed.
No re-entry on the same session. A session serves one host request at a time. A handler MAY call the host with Bridge.Call; what is refused is Bridge.Handle on its own session (it would be a loop), a verb issued from inside a host callback (a run posted there would wait on itself), and a Bridge.Call the host answers by calling back into the same session. A host that needs to ask a question while answering one posts it to another thread.

What a handler can count on

A handler that throws is not a bug in the contract: the dispatcher turns it into ok: false with the engine's own code, message, position and frames, which is why a verb a script did not anticipate still answers a document a host can read. A handler that answers something that is not an envelope (a plain string, nothing at all, an object with no boolean ok) is reported as HandlerReturnedNonEnvelope rather than forwarded to a host that would have to guess, and the same code covers an ok:true answer carrying e, an e that is not an object, and an error whose code or message is missing or not a non-empty string. An ok:false answer carrying r has the r dropped, because exactly one of the two shapes is present. The error's origin is forced by the dispatcher: "engine" when it or the engine built the failure, "handler" when the handler answered it. And the response's v and id are the dispatcher's, rewritten from the request by construction, null included, so a handler cannot echo the wrong id even by accident.

An absent p is legal, and an explicit null means the same, so a handler that indexes req["p"] unconditionally refuses a request the contract allows. Guard it: var payload = req.ContainsKey("p") ? req["p"] : null;. An absent id is legal too, which is why a handler echoes req["id"] rather than assuming one is there; a request that sent "id": null gets "id": null back.

Paging and retrying are the application's contract, not the engine's. A large result is paged inside p and r with the reserved $page, $next and $done keys, so a generic client can page a verb that opts in. retry: true invites the host to send the same request again: the handler owns making that safe, and id is the correlation handle and the natural idempotency key, because the dispatcher does not dedupe. No carrier allows two requests outstanding at once, so a host sends its requests in sequence; pipelining would need a batch, which this version does not define.

How the two doors are carried

CarrierThe two doors
The C ABIslc_invoke(handle, requestJson, buffer, capacity) drives the script side, answering the length the response document needs (the same snprintf convention every other output uses). slc_set_bridge(handle, callback, user) installs the host side as int32_t (*)(int64_t handle, void* user, const char* request, char* buffer, int capacity), with a NEGATIVE answer meaning the host refused. Capability bit 0x200.
COMThe same object that runs scripts has an Invoke(requestJson) member: one argument, one document in, one document out. It forwards to the script door above rather than to a second dispatcher, so a VBA client and a C host speak one contract.
.NETA host that holds the interpreter directly sets HostBridge, a Func<string, string?>, which is the same field slc_set_bridge writes. There is no second implementation of the rule.

Two kinds of failure, kept apart on purpose. A CONTRACT failure (an unknown verb, another version, a handler that threw) is a normal answer and travels INSIDE the document as ok: false, so a host reads one shape. A TRANSPORT failure (no such session, a session already running, a freed handle) is not an answer at all: the ABI answers a negative status with the reason on slc_last_error, because putting a sentence in a buffer the host parses as JSON is how a binding ends up reporting a parse error instead of the real problem. Over COM, where a member has no status to answer, a transport failure is the sentence in LastError. A dedicated page, docs/bridge/howto.html, takes the contract and all five carriers end to end, with a complete sample for each: C, C#, Python, PowerShell and COM.

assets/language/repl/interop/bridge_contract_test.slc is this contract pinned against an in-process stub host: the version, the verb, the parameters object including an explicit null, a handler being served, a handler's own failure, a re-entrant call and a handler calling the host while serving, the answer's whole shape (exactly one of r or e, and the error's code, message, origin, retryAfter and details), a response that names somebody else's id and version, and the id echoed (anonymous, numeric, string and null). The two carriers have their own proofs: src/embed/Program.cs drives both doors over a real function pointer, and the COM member is driven from a registered COM client.

Com COM interop create objects, access properties, call methods via IDispatch, embed ActiveX controls in windows (Com.HostActiveX), and reach the application that hosts the engine (Com.Host)

COM (Component Object Model) automation via native IDispatch vtable calls. All operations are AOT-compatible (no reflection, no dynamic). Every COM object the bridge hands back is tracked in a ComScope, and the scope releases the bridge's references to them when it exits see the lifecycle below for what that does, and what it does NOT do.

This namespace is the CLIENT side: a script driving Excel. The engine is also a COM SERVER, so the direction reverses for a host that cannot declare the C ABI: CreateObject("ScriptLangCore.Session") in VBA or VBScript answers an object whose RunText, Eval, LastResult and LastError members run scripts in this engine. The eight members are in the ScriptLangCore.Session entry below, and the registration and the workbook example are on the embedding page, under "The DLL as a COM server".

The whole surface eight methods

MethodWhat it doesWhose the application is
Com.Run(callback [, extraArgs…])Turns the thread into an OLE/STA apartment, creates a ComScope and calls the callback with it, and returns the callback's value. At its LAST scope out it releases its interfaces and reports every server this process started that nothing quit.Nothing is ended here the script quits, inside the callback.
Com.CreateObject(progId)Starts a fresh instance (a ComNode), and records it as this process's own work.Yours: call Quit() on it, or the run reports it.
Com.GetObject(progId)
also (path, progId)
Finds a running instance through the Running Object Table the ATTACH path. Nothing is recorded.Its owner's: never reported, never touched.
Com.GetOrCreate(progId)Attach-or-create in one call: it reuses a running instance, and starts (and records) one when nothing of that class is up.Decided by which half it took see the two rows above.
Com.IsAlive([progId | node])Is it still there, or still usable? Prefer the scoped forms. A node: is THIS handle still usable? the tightest scope, answered without dispatching when its run released it, so it is safe on a handle held past its run. No argument: has THIS PROCESS started anything still up? A ProgID: is anything of that class running? the loosest scope, and the only one that cannot tell YOUR instance from a stranger's. The tool for waiting out a real shutdown instead of guessing a sleep.Answers the lifetime question without taking a side.
Com.Stats()The bridge's counted facts: name lookups and hits, parameter lookups and hits, safe arrays created/destroyed, enumerations, the process handle count, type-cache entries, and StillRunning / .StillRunningNames. Every property is dynamic.Reads only it ends nothing.
Com.Host([strict])The object of the application hosting this engine (the Excel instance whose VBA macro started the engine inside it), or null when nothing was adopted. The optional strict (true) refuses with the reason instead of answering null. Inside Com.Run, like every other member here.The HOST's: never quit here and never reported, and the engine holds the reference only while a run uses it.
Com.HostActiveX(node, parentHwnd [, x, y, w, h, verb])Hosts an ActiveX control in-place inside an existing Win32 window and returns the control's child HWND.The control and its OLE site live on the STA thread see its own section below.
Eight methods is the WHOLE surface, and none of them ends an application. Quitting is the script's line to write (Quit(), inside the callback), and the engine's part is to REPORT what was left running which is what the lifecycle below describes.

Lifecycle Com.Run(callback)

All COM operations MUST happen inside Com.Run(callback). It initializes the thread as OLE/STA (OleInitialize, which Com.HostActiveX needs for embedding ActiveX controls), creates a ComScope, and disposes it when the callback returns. The callback receives that scope as its parameter Com.Run((scope) => { … }) and a callback that ignores it (() => { … }) is equally fine. Anything after the callback is handed to it after the scope Com.Run((scope, progId) => { scope.CreateObject(progId); }, "Excel.Application") so a helper can pass values explicitly instead of relying on capture. Use the parameter to create objects in a scope you name yourself, which is what makes helpers and nested runs composable; Com.CreateObject is the shorthand for the scope that is current on the thread.

// the callback receives the scope its objects will be released by Com.Run(fun(scope) { var app = Com.CreateObject("Excel.Application"); // a ComNode: the CURRENT scope tracks it var fso = scope.CreateObject("Scripting.FileSystemObject"); // the same call, spelled with the scope print(fso.Drives.Count); // scope.GetObject(pathName, progId) also exists // nothing typed to end `app`: this run started it, so its last scope out ends it (below) });

scope is the tracker, not an object. It owns every COM object created inside its run and releases them when it exits, while app and fso are the objects themselves (ComNode handles) so app.Quit() and fso.Drives are the SERVER's members, and the scope has nothing to do with them. Inside one callback Com.CreateObject and scope.CreateObject are the same call: the first is the shorthand for the scope that is current on the thread, and that is this one. They differ only when the scope you mean is NOT the current one, which is the nested case inside an inner Com.Run, Com.CreateObject registers in the INNER scope (released when that block ends) while scope.CreateObject, with an outer scope value, registers in the OUTER one (still alive). So: use Com.CreateObject for the run you are in, and pass scope to a helper when its ownership should be explicit. Whose an APPLICATION is, the RUN decides rather than the scope: it ends the ones this process STARTED, and leaves an instance it merely attached to alone see the lifecycle below.

What "the scope disposes it" means 
WhenAt that scope's Dispose the end of its Com.Run, or the end of the nested block it belonged to. Deterministic: not the garbage collector's timing, and GC.Collect() has nothing to do with it.
What happensThe bridge releases its COM reference. For an IN-PROCESS server (Scripting.FileSystemObject, ADODB.Stream) the last reference going destroys the object, so it is gone once the scope exits usable until then. Repeated wrappers of one interface are deduped, so a scope releases each object exactly once.
What ELSE happens the reportWhen the LAST scope on the thread closes, the bridge REPORTS every application this process STARTED through Com.CreateObject or Com.GetOrCreate that is still running: a line on stderr naming it, plus Com.Stats().StillRunning / .StillRunningNames. It does not end it: quitting is the script's own Quit(), inside the callback. An instance this process merely ATTACHED to is never recorded, so it is never reported; an IN-PROCESS server has no server to quit and is never reported either.
The variable is not cleaned up that is the half people miss. When the scope exits it releases the interface, but the value in your variable is left untouched and nothing nulls it for you, so what you are holding is a dangling handle. What that costs depends entirely on the server:
  • an OUT-OF-PROCESS server (Excel, WMI) answers through its dead proxy with a clear error: the COM object is disconnected: its server is gone;
  • an IN-PROCESS server (Scripting.FileSystemObject, scrrun.dll) is freed memory, and calling into it kills the process SILENTLY: a run printed the object's value inside the scope, then stopped with no error at all when the same handle was used after that scope had exited. (Com.IsAlive(node) is the test for it, and it is safe to ask: a released handle is answered WITHOUT dispatching, so it does not become the crash it is asking about.)
So treat an object as valid only until the run that created it ends: do not stash it in a global, and do not use it after a nested block that owned it. If it must outlive the current block, create it in an OUTER scope that is what the scope parameter is for.
One out-of-process activation leaves one connection handle until that server exits. Measured with cdb's !handle: each Com.CreateObject of a LocalServer (Excel, WMI) leaves an ALPC Port the connection to that instance and 45 seconds after the instances had QUIT, with their processes gone, about 70% of those handles were still held. It is the COM/RPC runtime's handle, not a reference the bridge forgot to release: an IN-PROCESS server leaks nothing over 200 activations. So a program that keeps ONE instance per run costs one handle and then none, while a script that activates a server in a loop accumulates one per activation (bounded by the activations, never by time). If you must activate repeatedly, Com.GetObject attaches to the running instance instead of starting another; if the result is just a file, writing it directly avoids the activation altogether.
The engine does not end applications it REPORTS the ones you forgot to quit. When the run's LAST scope closes (the end of the outermost Com.Run, or an early scope.Dispose() taken while no other run is live), the bridge releases its COM interfaces so the handles from that scope stop working ("the COM object is disconnected: its server is gone") and then it looks, in the Running Object Table, at every server this process STARTED. Whatever is still there is named on stderr and counted in Com.Stats().StillRunning / .StillRunningNames. Quitting it was, and stays, the script's job: Quit() inside the callback, the only place its handles are alive. That division is deliberate an engine that quits a server is guessing at a lifetime that is not its own.
Two consequences, stated plainly. Quit() DISCARDS unsaved edits in a server this process started: marking a document Saved and closing it without saving is exactly what lets the server end, so a workbook the script never wrote to disk is gone when the script quits it. And there is NO engine-side opt-out in EITHER direction: the bridge never ends a server, so "keep it alive" is not a flag you set — it is simply not calling Quit(), which is the case the run reports — while a server the script DOES quit cannot be asked to survive the run. Com.CreateObject means "this process started it", and whether it outlives the run is the script's own Quit(). An instance somebody ELSE started is the opposite case and is never touched. If work has to outlive the script, write it to disk inside the run. And not every server can be ended this way: PowerPoint's Application.Quit is not reachable through IDispatch at all, so a PowerPoint this process started stays running even when the script does everything right, and the run's leftover report is the only signal there is. Excel and Word (with a document open) both end correctly when the SCRIPT quits them.
// the script quits it the engine only REPORTS what was left running Com.Run(fun() { var app = Com.CreateObject("Excel.Application"); app.Visible = false; app.Workbooks.Add().Sheets(1).Cells(1, 1).Value = 42; app.Quit(); // YOUR line: a forgotten one is reported, never fixed for you });
A forgotten Quit() is the case it exists for, and a script that DID quit is not reported any more. An application that keeps a document does not die with the scope: a workbook left DIRTY keeps EXCEL.EXE alive 25 seconds after the scope had disposed, and without the script's Quit() that process is an invisible window nobody notices which is exactly what this report names. The line reads [WARNING] [L244:C5] Com: 'X' may still be running; Quit() it inside the callback (Com.Stats().StillRunning), where the position is the LAST statement the run executed (the report is made after the run, so it belongs to no statement of its own) and names NO OWNER, because the Running Object Table matches by CLASS: it cannot tell your instance from a stranger's (a foreign instance of the same class gets reported too). Read it as "check this", not as a verdict, and when you want a precise answer ask per SCOPE instead: Com.IsAlive(node) for one handle, Com.IsAlive() for this process's own work. Give a real shutdown 10-15 seconds before counting processes as well.
THE RELEASE COMES FIRST: the scope releases its interfaces and only then asks the table, because an interface still held in this process is what stops an out-of-process server from exiting, so asking before the release could only ever answer "still running" and reported scripts that had already quit. Measured after that order: the table stops resolving 115 ms after the release, inside the 500 ms grace. A script whose last statement is Quit() therefore says nothing; one that never quits still gets the line.
AND A PRISTINE INSTANCE IS NOT REPORTED EITHER, which is the same rule one step further: an instance with no document and no window exits by itself about a second after the scope's references go, so once the release comes first there is nothing left to report. What the report names is the case that really leaks, an instance holding a document: give it a document (even an unsaved cell in a new workbook) and it survives the release, which is exactly what the line warns about. A later run can still end one of those by attaching and quitting it.
Wrap the run in your own helper when a script repeats the same bridge work. Com.Run hands its callback the scope FIRST and then every extra argument it was given, so a helper can take the body as a parameter and inject the subject itself: a typed delegate (Func<…>) or a generic method parameter both accept a script lambda.
The generic form is a helper in the language, not a namespace: a caller that injects a subject takes a FACTORY and a BODY, and using releases the subject when the body returns (a subject that is not IDisposable is simply not disposed that is what using means here).
// the generic caller, in the language: the factory makes the subject, `using` releases it object Scoped(Func<object> factory, Func<object, object> body) { using (var subject = factory()) { return body(subject); } } Com.Run(fun(scope) { print(Scoped(fun() { return scope.CreateObject("Scripting.FileSystemObject"); }, (fso) => fso.Drives.Count)); // 3 });
There is deliberately no Scope.Run / Method.Run in the surface. Two namespaces already own a Run, and each injects what it owns: Com.Run a Com scope (whose last scope out also reports unquit servers), Task.Run a task while Invoke is the NAKED dynamic call, injecting nothing and holding no lifetime. A generic X.Run would therefore be a second spelling of one of those jobs rather than a third behaviour, which is the reason Com.Dispose was removed instead of aliased.
// a reusable caller, in the language: the subject is injected, the body decides object WithFso(Func<object, object> body) { return Com.Run(fun(scope) { return body(scope.CreateObject("Scripting.FileSystemObject")); }); } print(WithFso((fso) => fso.Drives.Count)); // 3

Nested Com.Run scoped lifetimes inside one apartment

Com.Run nests: each call creates its own scope, and an inner scope releases the objects created in it while the outer scope keeps its own. The thread's apartment and the bridge's internal array bookkeeping belong to the last scope out, whichever that is, so an inner run can never tear down the state an outer one is still using.

Com.Run(fun() { var app = Com.CreateObject("Excel.Application"); // a book opened, read and released on its own, while the app stays alive Com.Run(fun() { var wb = app.Workbooks.Open(@"report.xlsx"); print(wb.Sheets.Count); }); // wb released here; app still alive app.Quit(); });
Excel wants \ in a COM path, and has its own idea of array shapes. Measured: SaveAs("C:/temp/x.xlsx") a folder that exists, a unique name, no leaked instances was refused, Excel rendering the path as C:\//temp/x.xlsx; normalize / to \ and pass a FULL path a bare name is not refused: Excel resolves it against its OWN documents folder and writes nothing where you looked, which is what Path.GetFullPath prevents. And Range.Value over more than ONE cell is an array-backed VARIANT (VT_ARRAY|VT_VARIANT): the engine reads it as a 2-D value, and for writing, a 1-D array maps to a row while a jagged array gives the 2-D shape a column needs (a 1-D list aimed at a column range was accepted and then broadcast its first value into every cell).
The shape that misleads. Com.Run(() => { Com.CreateObject("Excel.Application"); }); does not end that application: it REPORTS it, and the instance keeps running. Attached instances are the other side of the coin Com.GetObject, and the attach half of Com.GetOrCreate, is never recorded at all, so nothing about an instance somebody else started is ever reported or touched. A trap worth knowing while you are here: Quit() on an instance you ATTACHED to answers HRESULT 0x80004005, so attaching is not a way to end a server either its starter owns it.

CreateObject / GetObject / GetOrCreate

var obj = Com.CreateObject("ProgID"); // CoCreateInstance var running = Com.GetObject("ProgID"); // ROT lookup

CreateObject starts a new COM instance. GetObject finds a running instance via the Running Object Table.

Com.GetOrCreate(progId) is the attach-or-create idiom in one call: it reuses a running instance when there is one, and starts a new instance otherwise. That is the difference between ONE COM connection handle and one per activation a loop calling CreateObject each iteration leaks an ALPC Port per iteration while attaching leaks none, and the runtime reclaims an idle connection only after minutes. Which of the two happened decides who has to END it: an instance it had to CREATE is this process's own work, so the script quits it (and a run in which the script forgets is reported); an instance it merely found ALREADY RUNNING belongs to whoever started it, and the script must leave it alone querying it is fine, quitting it is not, and it is never reported.

An application is ended by the SCRIPT that started it, with Quit() inside the callback. The engine's part is the report above: Com.Stats().StillRunning (a count) and .StillRunningNames (the ProgIDs, comma-separated), raised at the end of every run for each server this process started and nothing quit. An instance this process merely ATTACHED to is not the script's to end and is never reported; an in-process object has no server to quit, so it is not reported either (it dies with the last reference). The record is cleared once reported, so one forgotten server is named once never twice, and never mistaken for an instance the USER starts later.

Com.IsAlive([progId | node]) is the same question from the SCRIPT's side, and it exists so a script can WAIT instead of guessing: Quit() returns long before the server actually leaves, so while (Com.IsAlive("Excel.Application")) { sleep(250); } is the honest way to know. The argument picks the question: a node asks "is this HANDLE still usable?" (true inside the run that owns it, false once that run released it and the false is answered WITHOUT dispatching, which is what makes it safe on an in-process handle whose memory is gone); no argument asks "has this process started anything still up?"; a ProgID asks "is anything of that class running?", where a true for an instance somebody else started is simply not yours to undo. Scope is why all three exist: ask about the HANDLE you hold when you have it, about THIS PROCESS's own work when you do not, and by class only when the question really IS about the class it is the one form that cannot tell your instance from a stranger's, which is why the report it mirrors is worded the way it is.

That wait is CROSS-RUN. An application cannot be gone while the run that holds its interface is still alive: polling Com.IsAlive() inside the run that created it stayed true for every poll the scope is keeping the server up. A LATER Com.Run holds nothing of its own, and there the answer turned false immediately (measured, 0 polls) once the earlier run had quit it. So: quit inside the callback, then wait in a following run if you need certainty. That wait asks BY CLASS on purpose, even though the scoped forms are preferred in general: the no-argument form answers about the names the engine still has on its books, and a name it has already reported is forgotten so it can answer false while the application is still up.
// one call, three questions the ARGUMENT picks which Com.Run(fun() { var app = Com.CreateObject("Excel.Application"); app.Visible = false; print(Com.IsAlive(app)); // true: is THIS handle still usable? print(Com.IsAlive("Excel.Application")); // true: is anything of that class running? (may be somebody else's) print(Com.IsAlive()); // true: did THIS PROCESS start something? app.Quit(); }); // the wait for a real shutdown belongs in a LATER run a run holding the interface keeps the server up Com.Run(fun() { while (Com.IsAlive("Excel.Application")) { sleep(250); } }); // ...and the safe way to ask about a handle you KEPT: a released one answers false without making the call var held = null; Com.Run(fun() { held = Com.CreateObject("Scripting.FileSystemObject"); }); Com.Run(fun() { print(Com.IsAlive(held)); }); // false its run released it, and asking cannot crash
A namespace answers the names it registered plus Dispose(), which is a rule rather than a hole. Dispose() is the by-name counterpart of what using does to an instance, and it resolves through IDisposable: for a namespace tree this run OWNS (an imported bundle) it really releases that tree, and for one with nothing to release it is simply a NO-OP which is what being IDisposable means. Every OTHER name a namespace never registered is REFUSED (Method 'X' not found in namespace) exactly like a typo anywhere else: resolution stops at what the namespace REGISTERED, so a name it never declared is refused rather than quietly doing nothing.

The record lives on the PROCESS, and an entry is cleared as soon as it has been reported, INCLUDING when the name no longer resolves the ROT is the only handle on "the current instance", so a spent name could otherwise be mistaken for an instance the USER starts later. A DIFFERENT process is never reached: nothing on the machine records who STARTED an instance, so nothing of another process's is ever ended or reported, which is exactly what keeps this surface away from a stranger's application. Two related facts worth knowing: Com.Run returns its callback's VALUE (var n = Com.Run(() => { … return 42; }) ), and the callback's scope parameter IS the lifetime handle, whose Dispose() is idempotent, so you may call it early which, when no other run is live on the thread, is when the report is made.

Host the application this engine is running inside

Com.Host([strict]) answers the COM object of the application that HOSTS this engine, i.e. the Excel (or Word) instance whose own code started the engine inside it. It is the one instance COM's own cache cannot name: measured from inside Excel, Com.GetObject("Excel.Application") finds nothing (the Running Object Table holds no entry for the instance that loaded the engine) and Com.CreateObject("Excel.Application") starts a DIFFERENT instance. So a host that wants the engine to drive IT hands its own pointer over first, which is slc_adopt in the C ABI and EngineAdoptHost(ObjPtr(Application)) in the VBA module this repository ships.

A missing host answers null, the rule every lookup here follows (a control name nothing holds, an absent dictionary key, ctx.Body on a GET), so a flow decides for itself. Com.Host(true) is the strict spelling and refuses with the reason instead: nothing adopted, an adopted object that is gone, or no Com.Run() scope to hold the reference.

// one shape that is safe in any run: a plain run answers null and does nothing Com.Run(fun(scope) { var xl = Com.Host(); // inside a host: this very Excel if (xl == null) { return; } // a plain run has no host, so it stops here print(xl.Name); // "Microsoft Excel" the measured answer });

It belongs inside Com.Run(callback), like every other member of this namespace: the pointer a host hands over is apartment-local, so it is taken on the thread that will use it, and that run's ComScope tracks it like any other reference it hands back.

And the engine holds the host reference only while a run uses it. The adopted object is registered in the COM global interface table when a run starts and revoked when that run ends, in both the synchronous and the asynchronous verb, so an idle engine holds nothing and the host application is free to quit by itself. That is what makes a macro which adopts, works and then lets Excel close behave: the application leaves. A script that stores a Com.Host() value somewhere outliving the run (a global, an Events producer) keeps the application alive through that value, which is ordinary COM lifetime rather than a leak: drop the value when you are done with it.

Two refusals worth knowing before you meet them: Com.Host(true) outside any Com.Run says Com.Host() needs a Com.Run() scope to hold the reference, and an argument that is not a boolean is refused by name (Com.Host takes one optional boolean (true to refuse instead of answering null), not 'int'). A plain run (the CLI, the REPL, a packaged script) has no host, so Com.Host() is null there by design. The workbook side of all this is the "Driving it from Excel and VBA" section of docs/embed/howto.html.

HostActiveX embed an ActiveX control in a window

Com.HostActiveX(ctrl, parentHwnd [, x, y, w, h, verb]) embeds any Com.CreateObject-able ActiveX/OCX control in-place inside an existing Win32 window (e.g. form.Handle) and returns the control's child window handle. It is a generic OLE host: IOleObject → SetClientSite → OleRun → DoVerb → GetWindow. IE (Shell.Explorer) and Windows Media Player (WMPlayer.OCX) are two validated instances the control only needs to implement IOleObject and tolerate a minimal site; automation servers (Excel/Word/...) are rejected with a clear error.

var child = Com.HostActiveX(ctrl, form.Handle); // 640x480 at 0,0 var child = Com.HostActiveX(ctrl, form.Handle, 0, 40, 900, 600);

The optional verb selects the activation verb: 0 (default) = AUTO try OLEIVERB_INPLACEACTIVATE and fall back to OLEIVERB_SHOW if the control refuses it; 5 = in-place only; -1 = show only. After hosting, drive the control through its normal IDispatch members (ctrl.Navigate(...), ctrl.URL = ..., …). The control and its OLE site must live on the same STA thread as the window's message pump keep everything inside one Com.Run on the main thread. To keep the child fitted to the form, adopt it with form.AdoptChild(child, insets…) (auto-sizes on resize); otherwise size it manually on the form's Resize event with ctrl.SetBounds(...). See assets/language/ui/demos/music_player.slc for a full working player.

// Example a web browser in a Form (see assets/language/ui/demos/web_browser.slc) Com.Run(fun(scope) { var form = Application.CreateForm("Script Browser"); // the window exists from here, hidden var ie = Com.CreateObject("Shell.Explorer"); var child = Com.HostActiveX(ie, form.Handle, 0, 40, 900, 600); form.Show(); // a control that PAINTS (Explorer) only loads once its window is on screen ie.Navigate("https://example.com/"); var title = ""; while (title == "") { Application.DoEvents(); sleep(100); if (ie.Busy == false && ie.ReadyState == 4) title = ie.Document.title; } print("page title: " + title); // "Example Domain" read through the hosted control Application.Run(); ie.Quit(); });
// Example a second, independent control: Windows Media Player (msdxm.ocx) // (regsvr32 C:\Windows\System32\msdxm.ocx first) see assets/language/ui/demos/wmp_ocx_test.slc Com.Run(fun(scope) { var form = Application.CreateForm("Media Player"); var wmp = Com.CreateObject("WMPlayer.OCX"); Com.HostActiveX(wmp, form.Handle, 10, 40, 480, 320); // hosted while the form is still hidden wmp.uiMode = "none"; // bare video area wmp.URL = "file.mp4"; // play a file wmp.settings.volume = 50; // nested dispatch object form.Show(); // LAST: everything is set up, the window appears once Application.Run(); });
ActiveX hosting prerequisites: the control's OCX must be registered (regsvr32) and match the process bitness (ScriptLangCore is 64-bit); the demo window needs a desktop session; Office Click-to-Run vfs OCX copies refuse standalone registration. Com.CreateObject returns ComNode values whose returned COM objects chain (ie.Document.title, wmp.settings.volume).

Native property syntax

Properties are accessed with natural object.Property syntax no explicit getters/setters.

excel.Visible = true; // set property var vis = excel.Visible; // get property → bool var pid = process.ProcessId; // get numeric property var mem = process.WorkingSetSize; // get numeric (long)

Native method calls

Methods are called with natural object.Method(args) syntax. Arguments are converted to VARIANT automatically.

excel.Quit(); // void method var wb = excel.Workbooks.Open(@"C:\file.xlsx"); // chained property + method var sheet = wb.Sheets("Sheet1"); // indexed property (COM method) var svc = locator.ConnectServer("localhost", "root\\cimv2");

Named arguments and optional parameters

COM methods take the same name: value spelling as script functions, so a parameter can be addressed by the name the server publishes:

wb.SaveAs("out.xlsx", AccessMode: 3, ConflictResolution: 2); // the names the SERVER knows, not positions: AccessMode = xlExclusive, ConflictResolution = xlLocalSessionChanges // (overwrite without asking) naming the pair settles the question instead of leaving it to the server

The bridge resolves the name through the object's type library (IDispatch::GetTypeInfo → ITypeInfo::GetNames), which returns a member's parameters in order, and then sends the parameter's position as its DISPID the mechanism VBA compiles AccessMode:= into. It is cached per object, member and name, so only the first named call on a given object pays for the type library. A name the server will not publish is refused with an error naming the parameter, never silently re-pointed at the next one: a value one position early turns AccessMode: 3 into FileFormat = 3, and Excel then writes a 7-byte text file named .xlsx. Naming a pair such as AccessMode + ConflictResolution is also how you settle a question the server would otherwise ask what to do about an existing file inside the call itself: with DisplayAlerts = false suppressing that prompt, Excel reports the opaque "Impossible de lire la propriété SaveAs de la classe Workbook", which reads like a broken bridge rather than a suppressed dialog.

// Workbook.SaveAs(Filename, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, …) // 1 2 3 4 5 6 7 8 wb.SaveAs(path, null, null, null, null, null, 3, 2); // positionally: xlExclusive, xlLocalSessionChanges
Positional recipe null for every gap. For a server whose names cannot be resolved, or when a positional call simply reads better, pass the arguments in order and use null for each parameter to skip. null becomes a VARIANT of type VT_ERROR carrying DISP_E_PARAMNOTFOUND that IS VBA's Missing, and the only thing that makes an optional parameter skippable at all. Stop at the last parameter you set; every gap before it needs one null.
Two limits worth knowing. A member's parameter list is read up to 24 names, and a name past that is refused rather than guessed at Excel has one member that exceeds the buffer (Application.Run, 32 names), so its last parameters cannot be addressed by name through the bridge. And the type library is only reached when the object has one: a server that publishes none yields the same loud refusal.
Judge a save by the FILE, not by wb.FileFormat. A never-saved workbook already reports 51 (xlOpenXMLWorkbook), so an assertion written against that number passes for a call that wrote nothing at all which is how a broken named-argument path once passed review while Excel answered "the method failed" and no file appeared. Check that the file exists, its size, and its PK header. A sheet/workbook layer built over this bridge struct handle, class, extension members lives in assets/language/com/com_excel_sheets_test.slc, and the gate's Excel coverage is assets/language/repl/com/com_excel_smoke_test.slc.

Com.Stats() what the bridge actually issues

Counters read at the call sites rather than inferred from timing. Each one is a live property, and they are process-wide. They answer the questions that keep coming up: what a shape really costs in round trips, whether a generator re-enters a collection, and how often a named argument pays for the type library.

PropertyMeaning
NameLookupsGetIDsOfNames calls issued for member names
NameHitsmember lookups satisfied by the per-object or per-type cache
ParameterLookupsGetTypeInfo + GetNames pairs issued for a named argument
ParameterHitsnamed-argument lookups satisfied by the per-object parameter cache
EnumerationsCOM collections for which an enumerator was created
Handlesthe process's kernel-handle count, read on demand the figure a COM or native leak consumes, and one no managed counter can see
SafeArraysCreatedSAFEARRAYs the bridge built for an array-valued argument or a block write
SafeArraysDestroyed...and destroyed. A FAILED destroy is not counted, so created == destroyed after a block write is the leak check. An array-valued property PUT is destroyed when its scope exits rather than at the call, because the server may still be reading it
TypeCacheEntriestype-level (vtable-keyed) dispid cache entries
var s = Com.Stats(); print(s.ParameterLookups + " lookups, " + s.ParameterHits + " hits");
Measured shape of the named-argument cache (JIT and the AOT publish agree): a named call on a NEW object costs one lookup; the same member+name on the SAME object is a hit; a second OBJECT pays again. It is per object, like the member cache and Excel hands out a new Range/Cells object on every access, so hold on to the object you mean to reuse.

Collection enumeration

COM collections are enumerated via .ForEach((item) => { ... }). Each item is a ComNode tracked in the current scope. Alternatively, use .AsEnumerable() to get a foreach-compatible iterator. Prefer the iterator form when the loop is hot: measured over 2,000 items, ForEach(fun) costs about 2,650 ticks/item against 1,870 for foreach + AsEnumerable(), because the callback form carries the lambda as a CLR delegate while the iterator feeds the script's own foreach. A script coroutine works too and costs almost nothing for script-side data (43 ticks/item against a 34-tick control), but driving a COM collection through one measured slower than both (2,379 ticks/item), so prefer AsEnumerable() over COM and yield over script data. Better still, avoid enumerating a collection for BULK data: one Range.Value read of 10,000 cells measured 6 ticks/cell against ~1,700 per ENUMERATED item, because each item is its own COM round trip. Read the block, then walk the script-side value.

For bulk writes, the lever is CALCULATION, not the screen. Measured on 500 ten-cell row writes over a sheet with a formula column, each configuration run twice with a baseline repeat as a drift check (assets/language/com/excel_speed_bench.slc): Application.Calculation = xlCalculationManual (-4135) cut the time by 35-40%, well beyond the run-to-run spread; Application.ScreenUpdating = false moved it less than that spread, both with the window hidden and with Visible = true the COM round trips and the recalculation dominate, and suppressing repaints has little to suppress. Restore the automatic setting afterwards. On the AOT publish the same bench measured Calculation = manual at -46% (-2,087,834 ticks) with a ~5% drift, and ScreenUpdating = false on a VISIBLE window at -0.35% nothing. The shipping build was also the QUIETER benchmark target (5% drift against 12-40% on the JIT build), so measure there.
VBA inside Excel, or the bridge from a script measured, per cell.
Same 1,000-cell write+read, minimum of seven samples with the work repeated inside each timed span (assets/language/com/excel_vba_bench.slc, AOT):
  • per cell, cell-by-cell loops: VBA 30 µs vs bridge 1.31 ms (VBA 43x faster)
  • per cell, BLOCK shaped: VBA 7 µs vs bridge 14.5 µs (VBA 2x a near tie)
  • one COM call: ~110 µs round trip, so the bridge's cost is per CALL, not per cell
  • the SHAPE is worth 4x inside VBA and 90x through the bridge more than the choice of side
Reading it: VBA wins per call because it never marshals; the bridge ties on a block, and wins on reach JSON, sqlite, files, regex, coroutines, structs, and a test harness which VBA does not have. So the question is not which side is faster but how many calls you make: for work that must stay inside Excel, VBA (or VBA's own block idioms); for anything needing the language, the bridge, shaped in blocks.
processes.ForEach(fun(p) { print(p.Name + " " + p.ProcessId); }); // or via foreach + AsEnumerable (used in WMI tests) foreach (var item in processes.AsEnumerable()) { print(item.Name); }

Bulk range operations (Excel)

Read/write 2D arrays to Excel ranges via SAFEARRAY:

range.SetRangeValues([["Name", "Score"], ["Jan", 42.314]]); var data = range.GetRangeValues(); // lazy row-by-row IEnumerable

Fluent API (alternate syntax)

Explicit get/set/invoke calls as alternatives to native syntax:

node.Get("Workbooks") // same as .Workbooks node.Set("Visible", true) // same as .Visible = true node.Invoke("Quit") // same as .Quit() node.Get("Range", "A1:B2") // indexed property get node.Set("Value", 42, "A1") // indexed property set

Example Excel automation

Com.Run(fun() { var excel = Com.CreateObject("Excel.Application"); excel.Visible = true; excel.DisplayAlerts = false; var wb = excel.Workbooks.Open(@"report.xlsx"); var sheet = wb.Sheets("Sheet1"); sheet.Range("A1:C3").SetRangeValues([ ["Name", "Score", "Grade"], ["Alice", 95, "A"], ["Bob", 82, "B"] ]); var score = sheet.Range("B2").Value; print("Score: " + score); });

That example opens a workbook and quits, but it does not release the book or mark it clean first see Lifecycle above for the recipe that reliably ends the process.

Example a block export: sqlite to Excel to CSV (advanced)

The shape that matters at scale: ONE Range.Value write for the whole table instead of one call per cell, a boundary query instead of a row scan, and the release recipe. The tracked sample is assets/language/com/sqlite_excel_csv_test.slc 50,000 rows, 9 checks.

// sqlite (in memory) -> a 2-D script list -> ONE Range write -> SaveAs CSV var rows = Sqlite.Query(lib, db, "SELECT id, Age, Name FROM people"); var grid = [].ToList(); foreach (var r in rows) { grid.Add([r.id, r.Age, r.Name]); } Com.Run(fun() { var app = Com.CreateObject("Excel.Application"); var wb = null; try { app.Visible = false; app.DisplayAlerts = false; app.Calculation = -4135; // xlCalculationManual: the bulk-write lever wb = app.Workbooks.Add(); var ws = wb.Sheets(1); ws.Range("A1:C" + grid.Count).Value = grid; // ONE call for the table wb.SaveAs(Path.GetFullPath("export.csv"), FileFormat: 6, AccessMode: 3, ConflictResolution: 2); } finally { try { wb.Saved = true; } catch (var e1) { } try { wb.Close(false); } catch (var e2) { } app.Quit(); } });
Judge the save by the FILE. wb.FileFormat == 51 is not evidence that anything was written a never-saved workbook already reports 51. Check the file's existence, its size and its PK header. And note the named pair in SaveAs: with DisplayAlerts = false, leaving Excel to decide what to do about an existing file makes it fail with an opaque message instead of asking.

Example WMI query

Com.Run(fun() { var svc = Com.CreateObject("WbemScripting.SWbemLocator") .ConnectServer("localhost", "root\\cimv2"); var processes = svc.ExecQuery( "SELECT Name, ProcessId, WorkingSetSize FROM Win32_Process"); processes.ForEach(fun(p) { print(p.Name + " PID: " + p.ProcessId); }); });

Example Scripting.FileSystemObject

Com.Run(fun() { var fso = Com.CreateObject("Scripting.FileSystemObject"); var folder = fso.GetFolder(@"C:\Windows"); print("Subfolders: " + folder.SubFolders.Count); print("Files: " + folder.Files.Count); });

Threading

COM Automation requires an STA thread. Com.Run initializes COM as STA automatically. The interpreter uses [STAThread] on the entry point.

ScriptLangCore.Session The engine as an in-proc COM server: one CreateObject answers eight members that run scripts, for a host that cannot declare the C ABI

ScriptLangCore.dll is also an in-proc automation server. A host that cannot declare the C ABI (VBA, VBScript, any automation client) reaches the engine through one ProgID, ScriptLangCore.Session, the way it reaches Excel, and the eight members below all work on ONE session of this engine.

Dim engine As Object Set engine = CreateObject("ScriptLangCore.Session") MsgBox engine.RunText("print(2 + 2);") ' 4: what the snippet printed MsgBox engine.LastResult ' the verdict of that run, as JSON Set engine = Nothing ' tears the session down

The eight members

MemberDISPIDArgumentsWhat it answers
Version()1noneThe engine's own line, with the runtime and the embed ABI revision.
RunText(source [, name])2the snippet, and an optional label for where it came fromWhat the snippet printed, with the trailing line break trimmed, or the verdict JSON when it printed nothing. A failing script raises nothing: the failure IS the verdict.
RunFile(path)3a .slc fileThe same answer for a file. A .slcbc bundle is refused by name, exactly as the C ABI refuses it.
LastResult()4noneThe verdict of the last run as JSON: Status, Ok, Error, Code, Message, Line, and Result when the run answered a value.
LastError()5noneThe sentence for the last failure, empty after a success.
Eval(name, arg1, ...)6a function an earlier run declared, then its argumentsThe function's return value. Arguments are ordinary VARIANTs, so a number, a string and a boolean cross as they are, and the member takes as many as the caller passes.
Free()7noneNothing: it tears the session down. A later call answers that the object has been freed instead of crashing, because one object holds one session.
Invoke(requestJson)8one request documentThe Bridge contract over this door: one document in, one out, from the same dispatcher slc_invoke drives. A contract failure is the document's own ok: false; a transport failure is the sentence in LastError, because a member has no status to answer. It does not write LastResult: the document is the answer.

One session behind the object

The session is created on the object's FIRST use, not by CreateObject, so a machine whose engine cannot start still answers an object that says why, member by member, in LastError. Every member then works on that one session's interpreter, which is what makes Eval able to call what an earlier RunText declared. Free() ends the session, and so does releasing the last reference. Two objects are two sessions.

RunText, RunFile and Eval are synchronous: the call returns when the script does. The engine runs the script on a thread of its own and waits for it, so a deep recursion works here, and a script that loops holds the caller (an Excel window included) until it returns.

What the door does not do

  • It is late bound. There is no type library, so the host sees Object: Dim engine As ScriptLangCore.Session does not compile, IntelliSense knows nothing about the members, and a misspelled member is the run-time error 438, "Object doesn't support this property or method". Member names are matched case-insensitively.
  • It is x64 only, because the DLL is. A 32-bit host cannot load it and answers error 429, "ActiveX component can't create object", which is the same message an unregistered class gives; the example module's failure branch names which of the two it was.
  • It keeps the C ABI's refusals, not its conveniences. There is no output callback and no asynchronous run on this door (the typed route, assets\language\stdcall\StdCall.bas, has both), so what a snippet prints is RunText's answer and the buffer to read afterwards is LastResult.

Registering it

The ProgID is ScriptLangCore.Session and the CLSID is {4A9D69C4-D9E6-4914-B7DF-ABC442BF5096}. Both name the ScriptLangCore.dll the installer already ships, so this door adds no file. Two ways to register: the installer writes the ProgID, the CLSID and InprocServer32 with ThreadingModel=Apartment, and removes them on uninstall; or setup\com-register.reg does the same for the current user, without admin, with the DLL path as one line a reader can correct. src\build\check-com-registration.sh compares the two identities across the server, the harness, the .reg and the installer, so one of them cannot drift.

The example module

assets\language\stdcall\ComEngine.bas wraps the members in one late-bound VBA module (Invoke is reachable straight on the object), and ComCallExample.xlsm in the same folder is a workbook that carries it, with two buttons that run ComDemoRun and the module's own RunComSelfTest. Two details of that module are worth knowing before copying it: EngineEval forwards at most three arguments, because a VBA ParamArray cannot be passed through a late-bound call (the Eval member itself takes any number), and the self-test returns its verdict (SELFTEST OK, SELFTEST FAILED: n, SELFTEST DIED: ...) instead of only printing it, so a driver asserts the answer. bindings\vba-com-check.ps1 -Build regenerates the workbook from the shipped module, and -Verify registers the class, opens the saved copy, asserts the module and its two buttons, and requires SELFTEST OK.

mcp.Use Register MCP tool call middleware logging, blocking, caching

The mcp namespace is available in MCP mode. mcp.Use(fn) registers middleware that intercepts every tool call before the handler runs. Middleware can log, block, cache, or modify tool calls.

The middleware receives the call as an McpContext and the pipeline's own continuation as an Action, so both can be declared: (McpContext ctx, Action next) => { ... }.

mcp.Use((McpContext ctx, Action next) => { print("tool=" + ctx.ToolName); next(); // continue to next middleware or tool handler });

Context properties

PropertyTypeDescription
ctx.ToolNamestringName of the tool being called
ctx.ArgslistArguments passed to the tool
ctx.Resultobject?Set to bypass handler and return directly
ctx.ErrorMessagestringSet it (or call ctx.Error("...")) to stop the pipeline with an error: the tool call is not run and the message is what the caller receives

Blocking a tool

mcp.Use((McpContext ctx, Action next) => { if (ctx.ToolName == "delete_file") { ctx.ErrorMessage = "blocked by policy"; return; // don't call next() } next(); });
tcp.Use Register TCP connection middleware RemoteAddress, Close

tcp.Use(fn) registers middleware for the connections the engine's own TCP server accepts: Server.Create(port, ...) then Server.Start(). The middleware runs on the accept thread, BEFORE the server reads anything from the socket, so it sees every connection alike, the ones the file handler would answer and the ones meant for a WebSocket. A tcp.Use registered after the server started runs too: the server holds the same pipeline.

The middleware receives the connection as a TcpContext and the pipeline's own continuation as an Action, so both can be declared: (TcpContext ctx, Action next) => { ... }. Calling next() lets the connection through to the rest of the chain and then to the server's own handling; returning without calling it stops the chain there.

Context properties

MemberTypeDescription
ctx.RemoteAddressstringThe peer endpoint as the server sees it (127.0.0.1:54321), which is what lets a middleware allow or refuse by address
ctx.Close()voidCloses the connection immediately: the rest of the chain does not run, even if this middleware calls next() afterwards, and the server does not handle the connection at all
tcp.Use((TcpContext ctx, Action next) => { print("connection from " + ctx.RemoteAddress); next(); // let it through to the rest of the chain });
// Refuse by address: Close() ends the connection AND the chain, so nothing else sees it tcp.Use((TcpContext ctx, Action next) => { if (ctx.RemoteAddress.StartsWith("192.168.")) { ctx.Close(); return; } next(); });
http.Use Register HTTP routes and request middleware

The http namespace is available in MCP+HTTP mode. http.MapGet and its siblings register an endpoint, and http.Use(fn) registers middleware for the requests no route matched.

http.Use((HttpContext ctx, Action next) => { if (ctx.Url == "/hello" && ctx.HttpMethod == "GET") { ctx.ResponseBody = "Hello!"; ctx.ResponseStatus = 200; return; } next(); });

Routes

http.MapGet(pattern, handler), http.MapPost, http.MapPut and http.MapDelete register an ENDPOINT rather than a middleware. A route table belongs to the application, so it is registered once on the http namespace and not on a request's ctx.

http.MapGet("todos/{id}", (HttpContext ctx, Dictionary args) => "<b>" + args["id"] + "</b>"); http.MapPost("todos", (HttpContext ctx, Dictionary args) => { var text = Http.ParseForm(ctx.Body)["text"]; // ... store it ... return "<ul>...</ul>"; });
RuleDescription
The patternMatched on the PATH, so the query string is ignored and a trailing slash is the same route. A segment is literal ("todos", "stats/fragment") or {name}, which captures one segment; the root is "/".
The handler(HttpContext ctx, Dictionary args) => { ... }, where args holds the pattern's {name} segments by name, as in args["id"]. Its RETURN is the answer, and there are four cases: a string is the body written as text/plain; an http result (http.Text, Html, Json, Status, NotFound, Created) decides its own content type and its own status; any other object (a { } literal, a class, a list) is serialized as application/json; and a byte[] is sent as bytes. A handler that writes ctx itself (or a void one) returns nothing, which is a 200 with an empty body. A handler may declare a THIRD parameter, CancellationToken ct, and then it receives the request's own ctx.RequestAborted, so its work can stop when the client goes away; the DECLARATION is what decides, so a two-parameter handler is untouched.
Resultshttp.Text(s) / Html(s) / Json(v) / NotFound([body]) / Status(code [, body]) / Created(location, value) / File(path [, contentType [, fileName]]) / Bytes(data [, contentType [, fileName]]) / Avro(records, schema [, options]) / StreamLines(source [, contentType]) / StreamEvents(source), where Created also sets the Location header. NotFound() with no argument is a 404 with no body, the way Results.NotFound() is, and NotFound(body) writes the text the script chose; Status(code) with no body is the same shape for any code. There is deliberately no Ok beside Status(200, ...), and no TypedResults either: what makes a result "typed" is a compile-time return type, which a script does not have. Avro(records, schema [, options]) answers an Avro OBJECT CONTAINER FILE typed application/avro, the wire format AvroConvert's HTTP layer uses: the container is self-describing (its header carries the schema AND the codec), so a client decodes it from the bytes alone, and the options are Avro.WriteContainer's own ({ "codec": "zstandard" }). A single record is [record], because a container holds a sequence.
Files and downloadshttp.File(path) answers a file on disk: the bytes go out with an exact Content-Length and the content type is GUESSED from the extension with the very table the engine's own file server uses, so a route and that server cannot disagree about what a .pdf is. http.File(path, "", "report.pdf") and http.Bytes(data, type, "report.pdf") turn the answer into a DOWNLOAD with Content-Disposition: attachment, and a name that is not ASCII uses the RFC 5987 form (filename*=UTF-8''...), because a header is ISO-8859-1 by spec. http.Bytes takes a byte[] (what File.ReadAllBytes and Encoding.UTF8.GetBytes answer) or a list of numbers, and REFUSES one that is not a byte rather than truncating it. A route's ./x means beside the FILE THAT REGISTERED the route, captured when the route was registered, because a served request outlives the run that registered it. A .avro file is served as application/avro, because that extension is in the same table, so http.File("./orders.avro") and the engine's own file server agree with http.Avro about the type.
Streaminghttp.StreamLines(source) and http.StreamEvents(source) answer a body written ONE ELEMENT AT A TIME, with chunked framing: no Content-Length, because the length is not known when the answer starts, and one flush per element, so a client sees each line as it is produced. That is what makes a big export possible without holding it in memory. StreamLines writes one JSON value per line (application/x-ndjson, so a string arrives quoted), and StreamEvents writes data: <text> then a blank line (text/event-stream, so a browser's EventSource reads it natively; a multi-line value becomes one data: line per line, which the grammar requires). The source is a list, a generator, an Events feed, or an async sequence such as File.ReadLinesAsync(path): the producer is pulled on the request thread, so a script generator is resumed and an async step is awaited exactly as await foreach would. A feed is the one source with a condition: it must be created in inline mode, because a runThread feed delivers its values on the thread the run began on, which the writer is holding (one created that way is REFUSED, rather than losing values and leaving the server unable to answer). A stream is answered by a ROUTE HANDLER's return value: a http.Use middleware writes a whole body through ctx.ResponseBody and cannot stream, because a middleware returns nothing for the pipeline to interpret. Three things follow from the status going out with the FIRST element: an error part-way cannot change the status (the stream ENDS there, the client is told the body is incomplete, and the cause goes to the server's log), nothing that buffers may sit in front of the client (curl -N, or HttpCompletionOption.ResponseHeadersRead, or the batching is the CLIENT's), and a stream blocks the other requests this server takes while it is open, because it serves one request at a time.
The orderThe FIRST route that matches wins, in registration order, so a table is an ordered list rather than a specificity puzzle: "order/{x}" registered before "order/fixed" answers the wildcard. A pattern the table ALREADY holds is therefore a route that never runs, and registering it is REPORTED at warning level, naming the member, the pattern and the file that registered it: the table lives for the session, so a second .run of the same file re-adds its routes (harmless, it is reported), and a tool the --mcp startup loaded from <exe>/tools keeps what it registered first. That is the one collision worth knowing: the engine's sample mcp_httpserver.slc serves GET /, so a page route registered by a script you then .run never answers, and the remedy is --tools-dir pointing at a folder holding only your own tools.
Asking firsthttp.IsServed(method, pattern) answers whether THIS session already serves that method and pattern, so a program can claim a pattern only when it is free instead of registering a route that can never run: if (!http.IsServed("GET", "/")) { http.MapGet("/", page); }, which is what the htmx board does and why it stays silent in a session that kept the engine's sample tools (its page is always at /board as well). The comparison is the table's own, so "/x/" and "x" are one pattern and the method follows the interpreter's case rule; both arguments are strings, and a call without them is refused by name.
No matchnext(), exactly as a middleware that does not answer, so an http.Use middleware registered after the routes can still handle the request, log it or 404 it. The engine's 404 line then names what the session does serve (nothing is registered for '/todos'. This session serves GET /, GET time, POST echo, from mcp_httpserver.slc.), because a route that is missing because its file never ran looks exactly like a typo otherwise: a session with the engine's sample tools loaded has six routes registered from mcp_httpserver.slc, which is what --tools-dir pointed at an empty folder keeps out of the way.
Who writes the bodyA status the engine sets carries NO body, and a status the script chose carries what the script wrote. That is ASP.NET Core's rule: a request nothing answered is a 404 with Content-Length: 0 (the "page not found" text a browser shows for it is the browser's own), an unhandled exception is a 500 with no body in production, and 204/304 never carry one by spec. So a 404 an app wants to explain is http.NotFound("...") or ctx.ResponseBody; a 500 an app wants to explain is ctx.ErrorMessage = "...", whose text IS the body. When the engine answers instead, the reason goes to the server's LOG rather than into the response, so nothing is lost for the author and nothing is invented for the caller. The engine's own file server follows the same rule (404, 405 with Allow: GET, 403, all with no body).
A method as a handlerBoth http.Use and the Map* members take a function or a bound method: a method named where a field would be is its own value, so http.Use(app.Handle) carries app's receiver with the method. A value that cannot be called at all is refused by name, never dropped.
An async handlerA handler may be async, and its value IS the answer: the pipeline waits for the Task a script async body answers, then uses its result exactly as it would a synchronous one. A failure after an await becomes the 500 whose cause goes to the server's log, like any other handler failure. Two limits are properties of THIS server rather than of the language, and both are worth knowing before reaching for await: it serves one request at a time on one thread (a script's interpreter is thread-affine, so serving concurrently would run two bodies at once on one interpreter), and a handler must therefore never await a request to its own server, because that request can only be served after this one returns. Calling another service is the shape that works. A THIRD parameter is the request's own CancellationToken ((HttpContext ctx, Dictionary args, CancellationToken ct) => { ... }), which fires when the client goes away, so an await can be cancelled with it; that token is cancelled when a WRITE to the client fails, which is the only evidence this server gets of a disconnected client.
Describing a routeA registration takes a THIRD argument that says what its payloads look like, and that one statement both PUBLISHES the shape and ENFORCES it: http.MapPost("/users", handler, { "request": { "name": "Bob" }, "response": { "id": 2 }, "side": "both", "status": 201 }). The keys are sample (what a shape is inferred from, the way Json.ToOpenApi infers from one), request and response (one sample per side when the two differ), schema (an inline schema, for what a sample cannot establish: required, an int64, additionalProperties: false), side (request, response or both, defaulting to request for a POST, PUT or PATCH and response for every other method, which is what a registration usually means), status (the documented response code, 200 by default), summary, description, tags, rootName (the component name, derived from the pattern when absent), required (none or sample), formats, additionalProperties, validate, requestContentType and responseContentType (the MEDIA TYPE each side is in: a sample describes a JSON shape, so a route that answers HTML, an image or plain text can only say so by stating its type, and the type is published verbatim as a type/subtype, without a header parameter). A key it does not know is REFUSED at the registration that wrote it, by name, with that line's position, so a description cannot quietly mean nothing, and a media type stated for a side the route does not publish is refused the same way, because side is what decides whether the document can say it.
The documenthttp.OpenApi([options]) answers ONE OpenAPI 3.0.3 document for the whole table, so a session can describe itself instead of assembling a spec by hand: one path item per path with every method registered for it, summary, tags, requestBody and responses[status] from what each registration said, and ONE components block shared by every operation (a shape two routes describe is written once and referenced with $ref). A stated media type is what an operation's content is keyed by, application/json when the route stated none, and a route that states a type with NO sample is written as an empty media entry whose description names the type, which is the honest way for a route that answers HTML to appear at all. Its options are the DOCUMENT's: title, version, description, server (written as servers[0].url), extract (on by default here, unlike Json.ToOpenApi, because a document with several operations would otherwise repeat every shape in each of them; false inlines), additionalProperties and pretty. An endpoint nobody described is still LISTED, with a response that says its shape is undocumented, because a spec that hides a route the server answers is a spec a client author trips over. It is built when it is ASKED for, so a route registered later is in it, and two calls answer byte-identical text.
Serving ithttp.MapOpenApi([path [, options]]) serves that document, at /openapi.json unless a path is given, as application/json. It registers an ordinary GET route in the same table, so http.IsServed("GET", "/openapi.json") answers and a second registration warns like any duplicate. The options are the document's, so http.MapOpenApi({ "title": "Users API" }) serves and names it in one call.
EnforcementA described route REFUSES a request body that contradicts its published schema, before its handler runs: a 400 whose body is the sentence naming the first mismatch (the request body does not match this route's schema: $.id: expected an integer), and the same line goes to the server's log. Three things are deliberately not checked: a body whose CONTENT TYPE is not JSON (a route taking form-encoded or binary data never claimed a JSON shape), a body an earlier middleware already read as bytes or line by line, and anything at all when the route says "validate": false. An EMPTY body is checked like any other value, so a route whose schema wants an object refuses a request that carried none, which is what the document's requestBody: required promises. A contradicting ANSWER is REPORTED in the log rather than rewritten, because the client is already waiting for it.
// A documented API: the third argument publishes the shapes, and they are enforced http.MapGet("users/{id}", (HttpContext ctx, Dictionary args) => http.Json(Find(args["id"])), { "sample": { "id": 1, "name": "Ann" }, "summary": "One user", "tags": ["users"] }); http.MapPost("users", (HttpContext ctx, Dictionary args) => http.Created("/users/8", { "id": 8 }), { "request": { "name": "Bob" }, "response": { "id": 8 }, "side": "both", "status": 201 }); http.MapOpenApi({ "title": "Users API", "version": "1.0.0" }); // GET /openapi.json // POST users with {"name": 5} never reaches the handler, and the client is told why: // the request body does not match this route's schema: $.name: expected a string
// A tiny JSON API: a result decides the status and the type, a plain object is serialized for you http.MapGet("/", (HttpContext ctx, Dictionary args) => "<h1>Tasks</h1>"); // text/plain http.MapGet("todo/{id}", (HttpContext ctx, Dictionary args) => { "id": args["id"] }); // application/json http.MapGet("missing", (HttpContext ctx, Dictionary args) => http.NotFound("no such todo")); // 404 http.MapPost("todo", (HttpContext ctx, Dictionary args) => http.Created("/todo/7", { "id": 7 })); // 201 + Location http.MapDelete("todo/{id}", (HttpContext ctx, Dictionary args) => http.Status(204)); // no body http.Use((HttpContext ctx, Action next) => { print(ctx.HttpMethod + " " + ctx.Url); next(); // no route answered, so this one runs }); // An ASYNC handler: its value is the answer, and a failure after the await is the same 500 as any other async Task<string> Report() { await Task.Delay(20); return "ready"; } http.MapGet("report", Report); // A file, and a DOWNLOAD named report.pdf (the type is guessed from the extension) http.MapGet("file", (HttpContext ctx, Dictionary args) => http.File("./report.pdf", "", "report.pdf")); // An EXPORT that streams: one JSON value per line, written as the generator produces it int Rows() { for (var i = 0; i < 5000; i = i + 1) { yield { "id": i }; } return 0; } http.MapGet("export", (HttpContext ctx, Dictionary args) => http.StreamLines(Rows())); // An IMPORT of the same shape, read line by line, counting the lines it cannot use http.MapPost("import", (HttpContext ctx, Dictionary args) => { var ok = 0; var bad = 0; foreach (var line in ctx.BodyLines()) { try { var row = Json.Parse(line); ok = ok + 1; } catch (var e) { bad = bad + 1; } } return { "imported": ok, "skipped": bad }; }); // Server-sent events, and the request's token as the optional third parameter http.MapGet("ticks", (HttpContext ctx, Dictionary args, CancellationToken ct) => { var feed = Events.Create("inline"); feed.Start(fun(EventSubject self) { while (!self.Closed && !ct.IsCancellationRequested) { sleep(1000); self.Next("tick"); } }); return http.StreamEvents(feed.ReadOnly); });

Context properties

The request arrives as an HttpContext, so a middleware or a handler may pass it to a helper typed with its real name: string Panel(HttpContext ctx) { ... }.

A RESPONSE header is set with ctx.ResponseHeaders["X-My-Header"] = "value", the flat shape the other fields on the context already have (ctx.ResponseStatus, ctx.ResponseContentType, ctx.ResponseBody, ctx.ResponseBytes). ASP.NET spells it ctx.Response.Headers[...]: ctx.ResponseHeaders IS that dictionary here, because this context carries its own answer fields rather than a nested response object, and a second spelling of one thing is what this language retires rather than aliases.

PropertyTypeDescription
ctx.HttpMethodstringHTTP method (GET, POST, etc.)
ctx.UrlstringRequest path (/hello)
ctx.Bodystring?Request body for POST/PUT, as TEXT. It is read from the request the first time it is asked for, so a handler that never reads it costs nothing, and the answer is kept: reading it twice pays once. Null when the request carried no body, which is how a GET reads. A request body is read ONCE, so this and ctx.BodyLines() cannot both be used (the second one is refused by name). There is no size limit: this member is what reads all of it into memory.
ctx.BodyLines()IEnumerable<string>The request body LINE BY LINE, for a body too big to hold: foreach (var line in ctx.BodyLines()) { ... } reads one line at a time from the request's stream. A line is the raw TEXT, not parsed, so the handler owns the format and can skip and COUNT what it cannot use, which is what a bulk import needs. A body may DECLARE its length or arrive as a chunked stream with no length at all, and both are read the same way, so an upload never has to fit in memory. A line ends at CRLF, LF or CR alone, so a file written on Windows, on Unix or on an old Mac reads the same, and the terminator is never part of the line. Three rules: the body is consumed once (a second call, or a ctx.Body read, is refused by name); the lines are only readable while the request is being handled; and an aborted request THROWS at the next line rather than ending quietly, so a truncated import cannot read as a complete one. If a handler ASSIGNS ctx.Body first (to normalise or decompress what arrived), the lines read come from that text rather than from the request, which is what ctx.Body itself reports.
ctx.BodyChunks([chunkSize] [, token])IAsyncEnumerable<byte[]>The request body as a SEQUENCE OF CHUNKS, for a body that is neither text nor small enough to hold: await foreach (var chunk in ctx.BodyChunks(1048576)) { writer.Write(chunk); } writes an upload to disk one chunk at a time, so the largest thing in memory is one chunk. Each chunk is a freshly allocated array of exactly the bytes read, so it stays valid after the next pull. chunkSize defaults to 64 KB and is clamped to 1 KB up to 8 MB, so a typo cannot ask for one allocation of the whole body; token is asked between chunks (a handler that cancels its own CancellationTokenSource stops at the NEXT chunk), and ctx.RequestAborted is asked there too. The body is read ONCE: this door, ctx.Body, ctx.BodyLines() and ctx.RequestBytes exclude one another, each refusal naming the door already used, and the sequence ITSELF opens once (a second await foreach over it is refused rather than reading a half-consumed stream). A body whose length the request DECLARED is compared at the end, and one that stopped early THROWS rather than reading as a complete file; a request with no body answers an empty sequence. ctx.BodyChunks() is the save side of an upload, and File.OpenWriteBytes is the handle it writes through. Measured: a 2,684,354,560-byte (2.50 GiB) upload went through the htmx board's own route in 20,480 chunks in 12.8 s and the saved file was byte-identical to the source.
ctx.RequestBodyLengthlongThe number of bytes the request DECLARED in its Content-Length, or -1 when it declared none (a Transfer-Encoding: chunked body, or a body the program set). ctx.BodyChunks() compares what it read against it, and a handler reads it for a progress line or for its own completeness check.
ctx.ResponseStatusintHTTP response status (default 200)
ctx.RequestHeadersDictionaryRequest headers. Read one by name, ctx.RequestHeaders["HX-Request"]; an absent header answers null, so no guard is needed
ctx.RequestAbortedCancellationTokenFires when the client goes away or the request times out
ctx.RequestBytesbyte[]?The request body as BYTES, for a body that is not text: an Avro container, an image, a zip. It reads the request's stream RAW, so nothing decodes a binary payload as UTF-8 on the way in. The three rules are ctx.Body's, for the same reason: the body is consumed once, so a read through this door and then through ctx.Body or ctx.BodyLines() is REFUSED by name rather than answered half-consumed; a request with no body answers null; and a body the PROGRAM set is that text's UTF-8 bytes, which consumes nothing. Avro.ReadContainer(SlcFile, ctx.RequestBytes) is the pair it exists for, with http.Avro(...) on the answer side.
ctx.ResponseBodystring?Response body text
ctx.ResponseBytesbyte[]?Response body as bytes, for an icon or any binary answer
ctx.ResponseContentTypestring?Content type of the answer, for anything that is not HTML text
ctx.ResponseHeadersDictionaryHeaders to send with the answer: a result's own Location, or one a handler sets itself (ctx.ResponseHeaders["Cache-Control"] = "no-store"). Written before the body, and a name the platform refuses is reported rather than dropped in silence
ctx.ErrorMessagestring?Set it to refuse the request: the answer is a 500 whose BODY is this text, because the application is the one refusing. An UNHANDLED exception is a 500 with no body instead, with the cause in the log.
What a middleware can reach. It runs inside the request pipeline, on the interpreter that started the server, and it is a normal script body: it may call the file's own functions, read its top-level variables and use its classes, and it may name a CLR type as a static (Uri, Stopwatch, Version, IPAddress, CultureInfo, Regex). It can index the request's header dictionary directly, and a { } literal or a script list indexes as it does anywhere else. Http.ParseForm is still the way to read a whole form body: it splits the pairs and decodes each component once, so a multi-byte character survives, where Uri.UnescapeDataString would need the splitting and the + handling written out by hand.
StringBuilder Efficient string concatenation Append, AppendLine, ToString

For building strings efficiently without creating intermediate copies. Use new StringBuilder() to create one, then call Append() / AppendLine() to add content, and ToString() to retrieve the final string.

var sb = new StringBuilder(); sb.Append("hello"); sb.Append(" world"); print(sb.ToString());
// Build 100 lines O(n), single buffer var sb = new StringBuilder(); var i = 0; while (i < 100) { sb.Append("line " + i + "\n"); i = i + 1; } print(sb.ToString()); // 100 lines, single allocation // 1 MB stress test ~82 ms with StringBuilder vs ~4000 ms with + var big = new StringBuilder(); var block = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\n"; i = 0; while (i < 16000) { big.Append(block); i = i + 1; } print("1 MB: " + big.Length + " chars");
Performance: Using + to concatenate N strings creates N intermediate copies O(n²). Using StringBuilder grows a single internal buffer O(n). For large payloads (100 KB+), the difference is dramatic: 1 MB takes ~82ms with StringBuilder vs ~4000ms with +.
StrBuilder Script-friendly StringBuilder wrapper StrBuilder.Create()

The StrBuilder namespace provides a convenient wrapper around System.Text.StringBuilder that's ergonomic from script. StrBuilder.Create(initialCapacity?) returns a StringBuilder instance with chainable .Append(), .Clear(), .Length, and .Capacity.

var sb = StrBuilder.Create(); sb.Append("hello").Append(" ").Append("world"); print(sb.ToString()); // "hello world"
// With initial capacity var sb = StrBuilder.Create(256); // Chaining sb.Append("a").Append("b").Append("c"); print(sb.ToString()); // "abc" // Clear and reuse sb.Clear(); sb.Append("new"); print(sb.ToString()); // "new"
StringComparison String comparison mode

Enum values for controlling string comparison behavior in .NET method calls.

StringComparison.Ordinal StringComparison.OrdinalIgnoreCase
print(StringComparison.Ordinal); // Result: 4 print(StringComparison.OrdinalIgnoreCase); // Result: 5
DialogResult Message box result values

Numeric values returned by a message box use these for readable comparisons.

DialogResult.OK // 1 IDOK DialogResult.Cancel // 2 IDCANCEL DialogResult.Yes // 6 IDYES DialogResult.No // 7 IDNO
var form = Application.CreateForm("Confirm"); var result = form.MessageBox("Save changes?", "Confirm", 4); if (result == DialogResult.Yes) { print("User clicked Yes"); }
TypeInfo Type metadata at runtime

Provides type information at runtime. Access type metadata via the TypeInfo namespace.

// Access type info via TypeInfo namespace // Provides base type, nullable info, array rank, etc.
Process Launch and manage external processes

Launches external executables with optional stdout/stderr callbacks. Use proc.ExitCode (after WaitForExit()) to get the process exit code available immediately, no sleep() needed. Note: ExitCode returns -1 if the process has not exited yet (including after Kill() Windows does not set an exit code for killed processes). Stdout/stderr callbacks run asynchronously add sleep(300) after WaitForExit() when collecting output lines.

var proc = Process.Start("ffmpeg", "-i in.mp4 out.avi", fun(line) => print("[OUT] " + line), fun(line) => print("[ERR] " + line));
// Fire-and-forget var p = Process.Start("cmd.exe", "/c echo hello"); p.WaitForExit(); print("exit: " + p.ExitCode); // Capture output lines var lines = new List<object>(); var p2 = Process.Start("cmd.exe", "/c dir", fun(line) => lines.Add(line), null, null); p2.WaitForExit(); sleep(300); // drain async streams print("Got " + Count(lines) + " lines"); // Kill mid-execution var p3 = Process.Start("cmd.exe", "/c timeout 30"); sleep(500); p3.Kill();
// Exit code via WaitForExit preferred pattern var p4 = Process.Start("cmd.exe", '/c "timeout /t 5 /nobreak >nul & exit 42"', null, null); p4.WaitForExit(); print("Exit code: " + p4.ExitCode); // 42 works on any thread
Returns a ProcessHandle with .Kill() (safe on exited processes), .WaitForExit() (no-arg returns exit code, with timeout returns bool), .IsRunning, .ExitCode. The handle is IDisposable: using (var h = Process.Start(...)) { ... } releases it at the end of the block, h.Dispose() does the same by name, and h is IDisposable answers the question. Disposing releases THIS side's process handle and cached state, it does not end the process, so Kill() is what stops it. A QUERY on a released handle is refused with the engine's own sentence (this process handle was released: Dispose() ran, so the process cannot be queried) rather than the runtime's wording for it, which on an invariant-globalization build is its resource key; Kill() stays a safe no-op, as its contract says. Errors (Win32Exception) are caught and re-thrown as ScriptException with the native error code. Callbacks serialized per handle. WaitForExit() double-calls Process.WaitForExit() to drain async output streams. Add a sleep(300) after WaitForExit() when using callbacks.
File Read/write text and binary files

Provides text and binary file I/O: read, write, append, copy, move, delete, and size queries.

File.ReadAllText("data.txt"); File.WriteAllText("data.txt", "content"); File.AppendAllText("log.txt", "entry\n"); File.ReadAllLines("data.txt"); File.ReadAllBytes("data.bin"); File.WriteAllBytes("data.bin", bytes); File.Exists("data.txt"); File.Delete("data.txt"); File.Copy("src", "dst", true); File.Move("src", "dst"); File.GetSize("data.txt"); File.OpenWriteBytes("./data.bin");
File.WriteAllText("out.txt", "hello"); var content = File.ReadAllText("out.txt"); File.Delete("out.txt");

A relative path is resolved against the process directory, unless it starts with ./ or ../. "./data.txt" (and "../data.txt") means "in the directory of the script being run", which is also the process directory in the REPL. Any other relative spelling means "in the working directory the executable was started in", so "data.txt", "sub/data.txt" and the backslash form ".\data.txt" all name the SAME file, and none of them names one beside the script. An absolute path is used as given. This is the rule for Directory and for the bundle paths of Bytecode too.

// beside the script, wherever the process was started File.WriteAllText("./report.txt", "beside the script"); // beside the executable: a bare name is NOT "beside the script" File.WriteAllText("report.txt", "beside the exe"); // ask for either side explicitly print(Script.Directory()); // the run's directory print(Directory.GetCurrentDirectory()); // the process directory

A member this list does not hold is resolved on System.IO.File itself, so the whole .NET surface is reachable without being restated here: File.ReadAllTextAsync, File.GetLastWriteTime, File.OpenHandle. The members above always win, and two rules keep a fallback member behaving like them: a parameter that IS a path follows the ./ rule above, while an argument that is content stays exactly as written (WriteAllTextAsync(path, contents) resolves path and passes contents through), and a failure reads the engine's own way, naming the member and the position. A name neither the engine nor the type has is still refused, with the list of what this namespace holds.

// the task awaits like the engine's own var text = await File.ReadAllTextAsync("./report.txt"); print(File.GetLastWriteTime("./report.txt")); // a DateTime

Reading a file line by line. File.OpenRead(path) answers a reader you dispose: ReadLine() gives the next line without its terminator, and null at the end; ReadToEnd() gives every REMAINING line as a string array; Close() releases the handle, and a using block does that for you. A line ends at CRLF, LF or a lone CR, and no empty line follows a final terminator, so the reader and File.ReadAllLines answer the same rows for the same file.

using (var reader = File.OpenRead("./data.txt")) { var header = reader.ReadLine(); foreach (var line in reader.ReadToEnd()) { print(line); } }

Which one to use on a big file. ReadToEnd() and File.ReadAllLines keep every line at once: one string per line plus one pointer array, and an array over 85,000 bytes (about 10,600 lines) is allocated on the large object heap, which only a full collection reclaims. A ReadLine() loop keeps one line alive at a time, so it is the shape for a file too big to hold.

Writing bytes one chunk at a time. File.OpenWriteBytes(path [, append]) answers a FileByteWriter, the handle a save needs when the bytes never fit in one value. Write(data) appends a whole byte[] and Write(data, offset, count) a slice of one; Length is the file's length so far; Flush() pushes what is buffered; Close() (or a using block) releases the handle, after which a write is refused by name. UNTIL THAT CALL THE HANDLE HOLDS THE FILE: a second writer on that path is refused, and so is a delete, and what is still buffered (up to 64 KB) is not on disk yet, so an abandoned handle leaves a SHORT file rather than an empty one (a single Write larger than the buffer goes straight through). The engine does release a handle a script DECLARED and never closed when it disposes the interpreter, which for a script run from the command line is the end of the run: that is a net under a crash or an early exit, NOT a substitute for Close, because until it fires the file stays taken and the tail stays buffered. So a save closes in a finally, or opens inside a using block. The second argument makes it an APPEND, so a resumed transfer carries on instead of replacing the file. It exists beside File.OpenWrite because that handle is a TEXT writer, and writing a PNG through it would transcode every byte above 0x7F. ctx.BodyChunks() is the request side of the same pair, and the htmx board's upload route is the worked example: a 2.50 GiB upload written chunk by chunk came out byte-identical.

Where a script SAVES. A relative path is resolved BESIDE THE EXECUTABLE (the rule above), and an installed engine keeps that folder under Program Files, where a normal account may only read: a save written there fails on the machine a script is meant to run on, and it fails the same way for every script that forgets. So ask Application.DataPath first. It is the install's own data folder (created and granted Modify by the installer, which is the engine folder's own data in a repository or published tree and {app}\data beside {app}\bin in an installed one) or a declared SLC_DATA_HOME, and Application.DataWritable() says whether writing there will work, a SUBFOLDER included, before the first byte. The shipped tools all follow this: the htmx board keeps its database and its uploads there, the clipboard runner keeps its run store there, and a compiled build writes its output there. A path the USER names stays exactly as given: the rule is about where the engine's own files go, not about overriding a choice.

Directory Create, delete, list directories

Directory operations: create, delete (recursive), list files by pattern, list subdirectories, and query current directory.

Every path follows the File rule: "./x" is beside the script, and any other relative spelling is beside the executable. A member this list does not hold is resolved on System.IO.Directory itself, with the same rules as File (Directory.GetFileSystemEntries, Directory.GetLastWriteTime).

Directory.Exists("path"); Directory.CreateDirectory("path"); Directory.Delete("path", true); var files = Directory.GetFiles("path", "*.txt"); var dirs = Directory.GetDirectories("path"); Directory.GetCurrentDirectory();
Directory.CreateDirectory("output"); File.WriteAllText("output/test.txt", "data"); Directory.Delete("output", true);
Path Path manipulation utilities

Path segment combination, filename/directory/extension extraction, and path resolution.

Path.Combine("folder", "sub", "file.txt"); Path.GetFileName("C:\\dir\\file.txt"); Path.GetFileNameWithoutExtension("archive.tar.gz"); Path.GetDirectoryName("C:\\dir\\sub"); Path.GetExtension("data.json"); Path.ChangeExtension("photo.jpg", ".png"); Path.HasExtension("readme.md"); Path.GetFullPath("relative\\path.txt");
var full = Path.Combine("folder", "file.txt"); var ext = Path.GetExtension(full); // ".txt"
All methods delegate directly to System.IO.Path. Path separator is platform-specific (\\ on Windows, / on Unix). A member this list does not hold is resolved on System.IO.Path itself, with the same rules as File (Path.GetRandomFileName, Path.GetRelativePath).
pause Wait for key press

Blocks execution until the user presses any key. Useful in scripts before exiting, or between test phases.

pause;
print("Press any key to continue..."); pause; print("Continuing...");
exitcode Get/set process exit code

A reference cell (RefCell) that reads and writes the process exit code (Environment.ExitCode). Validates integer range.

exitcode = 0; print(exitcode);
exitcode = 42; abort(exitcode); // exits with code 42

▼ REPL Commands

.help Show the list of available commands

Displays a reference of all available dot commands, REPL features, and script expression/statement syntax. Grouped into Commands (all dot commands) and Expressions & Statements (script constructs available directly at the prompt).

In a FILE, a dot command is stripped before the file is read, so a session pasted into a script still runs: a line whose first character is . and whose name is one of these commands is removed (and .time / .echo are honoured, the way they are at the prompt). Both halves matter: a line that only looks like a command is left alone as code, so an indented .Replace(...) continues a chained call and .row .text { ... } inside a template stays part of its stylesheet.

.help
.help Commands .help Show this help .infos Show version, build info, AOT status .echo on/off Toggle echo mode .reset [all] Clear state ...
.exit / .quit Exit the interpreter

Exits the REPL and terminates the process. All interpreter state is discarded. .quit is a synonym.

.exit or .quit
.clear / .cls Clear the console screen

Resets the terminal and clears all visible text. A session with no console to clear, such as one whose output is piped into another program, is not an error: the command answers nothing and the prompt comes back.

.clear or .cls
.reset Clear all global variables and reset interpreter state. .reset hard creates a new Interpreter instance.
.reset
.reset all wipes user-defined types, classes, delegates, modules, and frees native library handles
.reset hard disposes the entire Interpreter and creates a new instance frees ALL state, caches, static dictionaries, and GC segments
.reset hard replaces the interpreter, so a session whose interpreter belongs to an embedding host is refused, with the reason, and pointed at .reset all, which clears the same state in place. .reset on its own clears the global variables too: keep them with .state keep when a .run is meant to inherit them.
Ctrl+C KeyboardInterrupt cancel current input or running script

Pressing Ctrl+C interrupts the current operation without exiting the REPL, like Python's behavior. A yellow Interrupted by user message is printed and a fresh prompt appears. Works both at the prompt (clears partial input) and during script execution (interrupts at the next statement boundary). When this session is serving HTTP (--mcp), pressing it also stops that server and says so: the prompt stays, and serving again is one .run away: a session launched to serve re-arms the listener when it runs a script. A session whose input is piped keeps the older rule instead and ends on the key, because there a closed input is the only other way out.

// At the prompt clears current line >>> KeyboardInterrupt >>> // During infinite loop interrupts execution while (true) {} // press Ctrl+C KeyboardInterrupt >>>
.vars List user-defined global variables (name, type, line, column)

Lists user-defined global variables in a formatted table with columns: Name, Type (script type name), Line, and Col (declaration location). Entries are sorted by declaration position. Only variables the user explicitly created are shown built-in namespaces, types, and functions are excluded.

.vars
.vars Name Type Line Col ────────────────────────────── x int 5 2 name string 10 3
.varsall [cat] List ALL global scope keys, grouped by category. Optionally filter by category name.

Categories: types, native, delegates, namespaces, functions, user, lists, dictionaries, ref cells, other. Multiple categories can be combined: .varsall types native.

.functions List user-defined functions, classes, and structs

Lists all user-defined declarations (functions, classes, structs) with their Name, Type, Line, and Column. Sorted by declaration order. Useful for checking the current scope after a series of REPL inputs.

.functions
.functions Name Type Line Col ────────────────────────────── square int 5 2 Point class 12 1
.tree <var> Display a variable's structure as a tree (lists, dicts, nested)

Displays a variable's structure as a visual tree. Supports lists, dictionaries, arrays, and raw .NET IDictionary types up to 10 elements (remaining are summarized as ... (N more)). Scalars show their ToString() value.

.tree variableName
.tree mydict mydict: Dictionary (3 entries) ├── name: Alice ├── scores: List [3] │ ├── [0]: 10 │ ├── [1]: 20 │ └── [2]: 30 └── tags: null
.strict Enable case-sensitive mode (default). 'A' and 'a' are distinct.

Enables case-sensitive identifier matching. After switching, MyVar and myvar refer to different variables. This is the default mode. Clears the method and property caches when toggled.

Keywords are case-sensitive in every mode: if is the keyword and IF is an ordinary name, so IF (x) { } is not an if statement and a whole number is written int, never Int. The same holds for a keyword used as a name, where the engine only warns for the keyword's own spelling: var class = 5; warns, var Class = 5; does not.

A type name follows the same rule. The engine registers string, int, long and their siblings, and refuses the CLR spelling in a declaration while naming the one to write: String name; reports write 'string'. A value's printed form is the engine's, too, so a string parameter and a concatenation render the same value the same way.

.strict
.lax Enable case-insensitive mode. 'A' and 'a' refer to the same variable.

Enables case-insensitive matching. MyVar and myvar refer to the same variable. Useful when working with imported code that uses inconsistent casing. When toggled, the method and property caches are cleared and a Reset(keepGlobals: true) is performed.

.lax
.time Toggle execution timing shows elapsed ms after each result

Toggles execution timing on/off. When on, each expression or statement shows elapsed milliseconds in parentheses after the result. Works like a stopwatch the time includes parsing, interpretation, and any I/O.

.time
.time Timing mode: ON >>> var x = 0; >>> while (x < 1000) { x = x + 1; } (1.23 ms)
.echo on/off Toggle echo mode each input line shown before execution (useful when piping)

Toggles echo mode. When ON, each input line is reprinted with the >>> prompt prefix before execution. Useful when piping scripts via stdin so you can see what was executed.

.echo on or .echo off
.echo on Echo mode: ON >>> echo on >>> print(42) = 42
.run <file> [-q|--quiet] [-bc [out.slcbc]] [-- <script args>] Execute a script file. Supports glob patterns, pipe-separated paths, and .state. -bc loads/builds the .slcbc sibling. -- passes the script its own arguments.

Executes a script file in the current interpreter context. Supports glob patterns (*.slc) and pipe-separated file lists. The file is resolved first as an absolute path, then relative to the configured base directory, then in assets/language/.

Whether state persists after execution depends on the .state setting (default: .state keep). Use .state reset to automatically clear all variables, classes, and modules after each .run.

A class, struct or enum a file declares therefore SURVIVES its run, which is what lets a later request reach it (an http.Use middleware calling a helper the file itself declared). Re-running the same file replaces its own declarations silently, so an edit takes effect; a different file declaring a name the session already has still warns (Class 'X' already declared. Skipping redefinition.) and keeps the first one.

.run "test.slc"
.run "stress_*.slc" // glob
.run "a.slc|b.slc" // batch
.run "tool.slc" -- a "b c" // the SCRIPT's own arguments

Everything after -- is the script's command line rather than another file, so a tool whose input IS its arguments can be driven from a session: .run slc-pack.slc -- launcher.exe app.slc app.exe --version 1.2.3.4. Inside the run, Application.Args is [the script's path, ...those arguments], which is exactly what the CLI gives a script, so a file written for the command line needs no second form. A QUOTED argument survives as one argument (-- "C:\Program Files\app.exe"), because a path with a space is the common case; only the tail is split this way, so .run a.slc|b.slc -bc is unchanged. Two rules to know: the arguments belong to that RUN and are put back afterwards, so the next statement reads the session's own Application.Args; and a script's arguments arrive with no shell, so a wildcard is not expanded (*.slc is the literal text) and there is no redirection or piping.

.run "test.slc reset" // run then clear state
.run "test.slc -q" // quiet: the script's own output is discarded
.run -bc "test.slc" // load the .slcbc sibling if present, else run the source and build it

A .run file runs exactly as the command line runs it, its top level included: the statements outside every function are compiled and run on the VM. A line TYPED at the prompt is the one thing that stays on the tree walker, because its value has to echo (= 42). The difference is not academic for a script that builds a window: the designer demo's setup measures about 0.5 s on the VM path and about 4.3 s walked, so routing FILE runs through the tree made the same file look ten times slower for no benefit.

-q and -bc belong to the command, not to the script. -q discards everything the run prints, and it does so at the ENGINE's writer as well as at Console.Out, so it silences the same way when the REPL is driven by a host (ScriptLangCore.Launcher.exe is one): a flag that only swapped Console.Out left a hosted run printing at full volume.

.looprun <N> <file> [-bc [out.slcbc]] [-- <script args>] Run a script file N times. Resets state between iterations unless .state keep is set. -bc also exports the .slcbc sibling.

Runs the specified script file N times in sequence. By default the interpreter is reset between each iteration, so each run starts with a clean state. Set .state keep to preserve variables across iterations (useful for incremental accumulation benchmarks).

Supports the same glob patterns and pipe-separated paths as .run. Catches per-iteration errors without aborting the benchmark. After all iterations complete, a summary line shows total time and runs/second.

Warning suppression: Non-critical warnings (e.g., "Variable already declared", "Class already declared") are automatically suppressed during .looprun and .bench to keep benchmark output clean.

What reaches the console while it runs: the FIRST iteration shows the script's own output, every later one is silenced, and one progress line (a percentage) is rewritten in place on stderr, so a 5000-iteration run reads as a single screen instead of a flood. The same rule holds when the REPL is driven by a HOST (the launcher is one): the silencing covers the engine's own output writer as well as Console.Out, which is the difference that used to let every iteration through into the host's pane. .run -q and .bench -q silence the same way.

.looprun 100 "test.slc" // 100 iterations
.looprun 1000 "stress_*.slc" // glob pattern × 1000
.looprun 5000 "lib.slcbc" // load a bytecode bundle 5000 times (no source parse)
.looprun 20 "bench.slc" -- 1000 // the SCRIPT's own arguments, each iteration

Everything after -- is the script's command line, the same rule .run follows, so a benchmark or a generator that takes its size from Application.Args can be looped from a session. Every iteration gets the SAME arguments ([the script's path, ...those arguments]), a quoted one survives whole, and the session's own list is back when the loop ends. Only the first iteration's output is printed by design, which is what a benchmark wants.

.looprun 50 "crash_memory_leak_fix.slc" // Output: // Running crash_memory_leak_fix.slc × 50 = 50 total executions... // Done: 50 runs in 12144 ms (4 runs/s)
.loadslcbc <file.slcbc> [alias] Load a bytecode bundle: library → namespace under alias (default file stem); single-script bundle → flat

Reads a .slcbc bundle (see Bytecode) and magic-detects its type. A library bundle becomes a Namespace defined under the given alias (default: the file stem) call its functions as alias.fn(...) (or alias.ns.fn(...) when the library declares namespaces). A single-script bundle loads flat: every function is defined into the current interpreter's global scope. Every body is decoded and verified at load, so a body that does not verify is refused here, naming the function, rather than when something first calls it. Prints the load report (e.g. Imported library as namespace 'lib'. or Loaded N function(s)).

.loadslcbc "C:/Temp/lib.slcbc" // library → namespace 'lib' (file stem) .loadslcbc "lib.slcbc" Z // library → namespace 'Z' (explicit alias) .loadslcbc "single.slcbc" // single-script bundle → flat
.loadslcbc "lib.slcbc" print(lib.sumTo(10)); // 55 library under namespace 'lib' (file stem) .loadslcbc "lib.slcbc" Z print(Z.sumTo(10)); // 55 same library, explicit alias 'Z' .loadslcbc "single.slcbc" print(sumTo(10)); // 55 single-script bundle loads flat
.state keep/reset Toggle whether .run and .looprun preserve or clear global variables between executions

Controls whether the interpreter state (variables, classes, modules) is preserved across .run and .looprun executions.

  • .state keep (default) state is preserved. Variables set by .run are accessible after it finishes.
  • .state reset state is cleared after each .run and between each .looprun iteration.
.state reset // clear state after each .run .state keep // preserve state (default)
.state reset .run "stress.slc" // clears globals after running .looprun 10 "test.slc" // each iteration is clean
.reset and .reset all are manual commands unaffected by .state they always clear state immediately regardless of the current setting.
Variable redeclaration warnings: With .state keep, running a script that declares variables (var x = ...) will print a warning when the same variable is re-declared in subsequent runs. The warning is informational the new value replaces the old. These warnings are automatically suppressed during .bench and .looprun.
.import <file> Import a script into the current session (keeps state no reset)

Imports a script into the current session without resetting state. Unlike .run, this keeps all existing variables, functions, and classes. Multiple imports accumulate. Equivalent to typing the file contents at the prompt.

.import "utility.inc"
This is the REPL equivalent of the import statement. It runs in the current interpreter's scope rather than creating a module interpreter. .include is the same command under its older name.
.cd [dir] Show or change the script base directory for .run and .import

Shows or changes the script base directory used by .run, .import, and glob resolution. When called without arguments, prints the current base directory. The path supports environment variable expansion (%USERPROFILE%).

.cd // show current
.cd "C:/Projects/Scripts"
.cd "%USERPROFILE%/scripts"
.debug on/off Enable or disable the interactive script debugger

Enables or disables the interactive script debugger. When enabled, you can set breakpoints with .break <line>. The debugger pauses execution at breakpoints and allows you to inspect variables. Toggle off to return to normal execution mode.

.debug on or .debug off
.break <line> Set a breakpoint at the specified line (requires .debug on)

Sets a breakpoint at the specified line number. The debugger must be enabled first (.debug on). Execution pauses when reaching that line, allowing variable inspection. Line numbers are relative to the current script or REPL input.

.break 42
.debug on .break 10 .run test.slc
.gc collect / .gc stats / .gc info / .gc diff / .gc top / .gc leak / .gc handles / .gc handletypes Show memory info, force garbage collection, show GC statistics, or run a one-shot leak check
.gc show memory usage
.gc collect force GC
.gc stats collection counts
.gc info per-gen sizes, fragmentation, pause
.gc diff memory delta since last .gc call
.gc top [N] top N object types by instance count (default 5)
.gc leak <file> [count] [thresholdKB] one-shot leak detector
.gc handles handle count and private bytes now, with the delta since the previous .gc handles/.gc collect

The OS-side counterpart of .gc collect: handles and private bytes are invisible to GC.GetTotalMemory, so a COM or native leak appears here and nowhere else. A count that climbs across repeated calls is a leak with one exception worth knowing: the connection handle a COM out-of-process activation costs (one ALPC Port) is reclaimed by the runtime within minutes of that server exiting (9 → 5 over a 4-minute idle), so read DELTAS rather than absolutes. The handle TYPE tally needs cdb (src\build\cdb-gc-leak.cmd -handles); this is the count, in-process, without a debugger.

Parameters:

  • <file> script to run repeatedly (fresh parse each iteration, like .looprun)
  • [count] number of measured runs (default 100; a warmup pass always runs first to absorb one-time startup state)
  • [thresholdKB] per-run retained-memory threshold in KB (default 64). If the measured per-run delta exceeds it, the verdict is LEAK; otherwise PASS. Raise it for scripts that legitimately retain per-run state; lower it to catch small leaks.

While it runs: the first measured run prints the script's own output and the rest stay quiet, with one percentage line rewritten on stderr, the same rule .looprun follows and for the same reason: a leak check of a few thousand runs must not bury its own verdict in script output.

Threshold noise floor: a thresholdKB below 16 KB is below the engine's GC allocator noise floor any workload trips LEAK on ordinary variance, not real retention. The command prints a warning in that case but still honors your chosen value. Use ≥ 16 KB (the 64 KB default is the calibrated value) for a meaningful verdict.

.gc info shows detailed memory diagnostics:

  • Heap total managed heap size
  • Fragmented memory lost to fragmentation
  • Gen0/1/2 size per-generation heap size
  • Paused duration of the last GC pause (important for real-time scenarios)
  • Frag ratio fragmentation percentage (high → compacting needed)
  • Memory load OS-reported memory pressure
// Typical output after a heavy bench: Heap: 96459.4 KB Fragmented: 12345.6 KB Gen0 size: 2100.3 KB Gen1 size: 8400.2 KB Gen2 size: 89100.0 KB Paused: 5.2 ms (last GC pause) Frag ratio: 12.4 % Memory load: 42.3 MB (OS) Gen0: 241 Gen1: 62 Gen2: 23
.gc diff Managed: +12.3 KB (delta since last .gc call) Gen0: +2 Gen1: +0 Gen2: +0 .gc top 1. ScriptBoxedDictionary 12,847 2. ClassInstance 8,492 3. Dictionary<String,Object> 6,103 4. List<Object> 4,221 5. ScriptFunction 2,018
// Memory-leak diagnostic workflow .gc top 10 → snapshot before .bench my_script.slc 100 -gc 50 -q → run 100 iterations .gc top 10 → snapshot after .gc diff → delta memory .gc history → collection counts + memory snapshot Gen0: 24 collections Gen1: 6 collections Gen2: 2 collections Memory: 12450.3 KB
Workflow tip: Chain .gc top 10 → .bench ... -gc 50 -q → .gc top 10 → .gc diff to identify memory leaks. If the same types grow linearly with iterations (visible in top before/after), clear the relevant caches or check for undisposed objects.
// One-shot leak check: baseline → run N times → forced collect → verdict .gc leak stress.slc 500 64 File: stress.slc × 500 Base: 363.8 KB After: 444.9 KB Retained delta: +81.1 KB Per run: 0.16 KB (threshold 64 KB) gen0=63 VERDICT: PASS no significant per-run retention // With a real leak (e.g. per-iteration rooted state): .gc leak leaky.slc 100 64 Per run: 31.25 KB (threshold 64 KB) VERDICT: LEAK retained memory grows per run and survives full collection
.gc leak automates the manual leak workflow in one command: it runs a warmup pass (absorbing one-time state like script globals, type registration, and cache warmup), measures a baseline after a forced full collection, runs the script count times (fresh parse each iteration, like .looprun), forces another full collection, and reports the per-run retained delta between runs. Growth that survives a full collection is rooted (a genuine leak e.g. a static or interpreter-held collection growing per iteration); reachable live state and one-time startup costs are absorbed by the warmup. Raise thresholdKB if a script legitimately retains per-run state; lower it to catch small leaks.
.history [N] Show last N REPL commands (default: all, max 500)
.history or .history 10

Multi-line entries show with indented continuation lines. Use .edit <line> to inspect an entry.

.edit <line> Display a history entry for editing

Shows the exact code from a history entry. Use .history first to find the line number, then .edit <N> to display it. Copy-paste and correct any typo.

.edit 1
.history 1 var x = 10; 2 var y = 20; .edit 2 2 var y = 20;
!<N> Re-execute a history entry (bash-style)

Type !<N> to re-execute history entry N. The entry is printed then executed. Useful for replaying commands or re-running a function definition after fixing it.

!3
.history 1 var x = 10; 2 var y = 20; 3 print(x + y); !2 >>> var y = 20; Warning: Variable 'y' is being redeclared at line 4.
.type Show type of an expression

Evaluates an expression and shows its type and value.

>>> .type 42 int => 42 >>> .type "hello" string => hello >>> .type 1 + 2 * 3 int => 7
Note: The expression is evaluated in the current interpreter scope, not a sandbox. Side effects (e.g. calling functions) persist.
.stats Show execution metrics

Shows uptime, statements executed, function calls, and managed memory.

.stats
.stats Uptime: 00:12:34 Statements: 1 523 Function calls: 342 Managed memory: 4.2 MB
.search <pattern> Search command history

Searches the interpreter's command history for lines containing the given pattern. The search is case-insensitive.

.search "pattern"
.search var History matches for 'var': 1: var x = 10 3: var name = "hello" 12: foreach (var i in range)
.alias Create or remove command aliases

Manages in-memory command aliases. Aliases are not persisted between sessions.

  • .alias list all current aliases.
  • .alias name=value create an alias (e.g., .alias ll=.looprun).
  • .alias name remove the specified alias.
.alias // list aliases .alias ll=.looprun // create alias .alias ll // remove alias
.alias ll=.looprun Alias 'll' => '.looprun' .alias ll => .looprun .alias ll Alias 'll' removed.
.eval <expression> Evaluate expression silently

Evaluates an expression without printing prompts. If the expression fails, the interpreter tries to parse it as a statement.

.eval x + 1
.eval 2 + 2 4 .eval var msg = "hello" // (no output statement executed silently)
.export [filename] | -bc <file.slc> [out.slcbc] [ns] | -bundle <file.slc> [out.slcbc] [--source=carry|strip|strict] Export variables to a script file, or -bc: run a script and export its VM-compiled top-level functions to a bytecode LIBRARY (.slcbc), or -bundle: write a PROGRAM bundle without running anything, with the source mode of --compile

Writes current user variables to a script file. If no filename is given, defaults to session_state.slc.

With -bc, instead of exporting variables it runs <file.slc> and exports its VM-compiled top-level functions to a bytecode LIBRARY (.slcbc). The optional trailing ns becomes the namespace for this script's functions in the library; functions the compiler did not take are skipped and reported. Load it back with .loadslcbc. A library names functions and namespaces and carries no source at all, so a source flag has nothing to act on here and is refused by name.

With -bundle, it writes a PROGRAM bundle instead: the artifact --compile writes and .run <file> -bc runs, with an entry. Nothing is executed, so a script that opens a window or never ends can still be compiled, and the compile happens in a fresh interpreter, so this session's own variables and classes cannot reach the artifact. The output path and the flags are the same as on the command line: the path is the first argument after the file that is not a flag, and --source=carry|strip|strict decides what the bundle carries (carry keeps the program text, strip strips it when the strip is honest and carries it otherwise, saying so in the report, strict refuses rather than carry, which is what --no-source means on the command line). Without a flag it carries.

Exported types: string, int, long, double, float, bool, null. Complex types (functions, classes) are skipped.

.export // writes to session_state.slc .export "backup.slc" // writes to backup.slc .export -bc "app.slc" // runs app.slc, writes app.slcbc as a bytecode LIBRARY .export -bc "app.slc" "app.slcbc" My // explicit output file + namespace 'My' for this script's functions .export -bundle "app.slc" // nothing runs; writes app.slcbc as a PROGRAM bundle, source carried .export -bundle "app.slc" --source=strip // the source is stripped when that is honest, and carried with a reason when it is not
.export myvars.slc Exported 3 variables to 'myvars.slc'. // Contents of myvars.slc: // var x = 42; // var name = "hello"; // var flag = true;
_ / _last Previous expression result variables

After every REPL expression evaluation, the result is stored in _ (most recent) and _last (previous). These are regular global-scope variables inspectable with .vars, usable in subsequent expressions. Note: REPL input requires a trailing ; for all statements, including variable references.

42; // = 42, _ = 42 _ * 2; // = 84, _ = 84, _last = 42 _last; // = 42 (previous value)
// REPL session: >>> 2 + 2; = 4 >>> _ * 10; = 40 >>> _last; = 4 >>> .vars _ = 40 _last = 4
Cleared on .state reset. Explicitly defining _ or _last in a script replaces the automatic values on the next expression evaluation.
.save [--all] [file] Export session state to a script file

Writes current user variables (and optionally declarations) to a script file for reuse. Defaults to session_state.slc.

Without --all: exports scalar variables (string, int, long, double, float, bool, null). With --all: also exports function, class, and struct declarations.

.save // writes to session_state.slc .save my_session.slc // writes to my_session.slc .save --all full.slc // includes functions and types
.save backup.slc Saved 3 item(s) to backup.slc // backup.slc contents: // var x = 42; // var msg = "hello"; // var flag = true;
.trace on|off Enable/disable execution call tracing

When enabled, prints [trace] lines showing every function call and REPL expression evaluation useful for debugging complex scripts or understanding control flow.

.trace on // enable tracing .trace off // disable tracing
// REPL session with trace on: >>> .trace on Trace: ON >>> var x = 2 >>> print(x); [trace] print(2) → null = null >>> 2 + 2; [trace] <repl> → 4 = 4
Function call tracing only fires for user-defined functions and script visible calls, not for internal built-in operations. Variable declarations and control-flow statements are not traced.
.vm [trace on|off] Inspect & control the bytecode VM trace toggle and enabled state

Interactive control of the bytecode VM, mirroring the script-side VmXXX built-ins.

.vm // show VM trace + enabled state .vm trace on // enable per-opcode VM tracing ([vm] ip=… OP sp=…) .vm trace off // disable
// REPL session: >>> .vm VM trace: OFF VM enabled: ON (.vm off re-enables the tree-walker...) >>> .vm trace on VM trace: ON
The trace sub-command toggles VmSetTrace(bool); the enabled/disabled state reflects VmSetEnabled(bool). Trace lines use the format [vm] fn=<name>[depth] [Lx:Cx] ip=N OP sp=N ; decode with a one-time --- source: <file> --- banner at file/import boundaries.
.bench <file> [N] [-q|--quiet] [-gc N] [-bc [out.slcbc]] Benchmark a script file (or a .slcbc bundle: loads it per run)

Runs a script file N times (default 10) and reports timing statistics. Reports total time, average time per run, and throughput (runs/s). Use -q or --quiet to suppress script output during benchmarking. Use -gc N to force a full garbage collection every N runs. The actual number of runs may be less than N if interrupted by Ctrl+C or if the script encounters an error.

.bench "test.slc" // 10 runs .bench "test.slc" 100 // 100 runs .bench "lib.slcbc" 100 // loads a bytecode bundle 100 times
.bench test.slc 50
.bench "test.slc" 1000 -gc 50 // GC every 50 runs`n.bench "test.slc" 100 -q // 100 runs, quiet
Runs: 50 Total: 2 340 ms Average: 46.8 ms Throughput: 21.4 runs/s
Note: State is reset between runs by default. Use .state keep before benchmarking to preserve state across iterations. When .state keep is active, SQLite database handles from setup scripts remain valid across all benchmark iterations they are not closed on reset.
Memory diagnostics: Combine .gc top 10 → .bench ... -gc 50 -q → .gc top 10 → .gc diff to detect memory leaks. If the same object types keep growing linearly across iterations, investigate the relevant caches (_pureMemoCache, _pureYieldCache) or undisposed object references.

Warning suppression: Non-critical warnings are automatically suppressed during .bench and .looprun execution to avoid noise in benchmark output.

.infos Show version, build date, AOT status, OS info

Displays system and build information: version number, file version, build date, Debug/Release configuration, AOT compilation status, .NET runtime version, OS description, process architecture (32/64-bit), and admin privilege status. Useful for diagnostics and confirming AOT compatibility.

.infos
.infos Version: 1.0.0.0 Configuration: Debug AOT compiled: No Runtime: .NET 11.0.0 OS: Windows 10.0.22631 Process: 64-bit Admin: Yes
.mcp List registered MCP tools (MCP server mode)

Shows all tools registered via RegisterMcpTool() and resources via RegisterMcpResource() with parameter signatures. Also lists built-in protocol methods (ping, initialize, logging/setLevel, resources/list). Only in --mcp --repl mode.

.mcp
.mcp Registered MCP tools (6): read_file(path: string) Read the full contents of a text file from disk. write_file(path: string, content: string) Write text content to a file. test_echo(message: string) Echo back the input. [Protocol methods: ping, initialize, logging/setLevel, resources/list]
.call <name> <json> Invoke an MCP tool directly

Calls a registered MCP tool with JSON arguments. Tests the same code path as the AI. Only in --mcp --repl mode.

.call test_echo {"message":"hi"}
.call test_echo {"message":"hi"} ECHO: hi .call test_add {"a":3,"b":4} Result: 7
.log <level> Set MCP server log level

Sets the MCP log level for diagnostic messages. Messages go to stderr. Only in --mcp --repl mode.

LevelShowsExample
debugEverything[MCP debug] → tools/call id=1
infoTool calls + errors[MCP infos] tool:system_info args:0
noticeSame as info (reserved)
warningErrors only
errorErrors only[MCP error] tool:read_file failed: ...
offNothing

.log off disables all logging.

.log debug
.log debug Log level set to: debug .log warning Log level set to: warning .log off Logging disabled.
> file Persistent stdout redirect all output goes to file

Redirects all REPL output (results, print, errors) to a file. Stays active until > console restores console output. Survives .state reset and works with .run, .import, .bench.

> file.txt 42 // goes to file.txt print("hi") // goes to file.txt > console // back to console
< file Execute a script file (alias for .run)

Shorthand for .run <file>. Same file resolution (direct path, glob, relative to script base directory).

< test.slc
REPL limitations:
  • Class declarations (class Foo {}) work in the REPL but instantiation (new Foo()) may not resolve the type immediately. Use .reset and retry, or define classes in a file and run with .run.
  • Multi-line input (e.g., function bodies, loops) is supported via ... continuation prompts.
  • Variables declared with var persist between commands. Use .reset or .reset hard to clear state.
  • Arrow keys (up/down) recall command history. Tab inserts a literal tab (no auto-completion).
  • Press Ctrl+C to interrupt a running script and return to the prompt.

▼ Sqlite Namespace

Sqlite SQLite cursor + UDF functions (requires sqlite3.dll loaded via LoadLibrary)

The Sqlite namespace provides high-level wrappers around the SQLite C API. It uses the same dynamic library handle obtained from LoadLibrary("sqlite3"). All cursor operations return IEnumerable objects that stream rows lazily the database is kept open until the enumerator is disposed. All handles use SafeHandle wrappers with critical finalizers to prevent native memory leaks. Methods that accept SQL parameters use params Array values can be passed as individual arguments or as an array literal.

Row access: by name or by ordinal

Cursor rows are returned as dictionary-like objects. You can access columns by name (r["id"]) or by ordinal position (r[0]). Both forms are equivalent ordinal lookup is O(1) and uses the query's column order. Mixed access within the same row is fine.

foreach (var r in db.Query("SELECT id, name, price FROM products")) { print(r["id"]); // by column name print(r[0]); // same by ordinal (0 = first column) print(r[1] + " $" + r[2]); // name + price by ordinal }

Methods

MethodReturnsDescription
Query(path, sql[, params]) or Query(db, sql[, params]) or Query(lib, path, sql[, params]) or Query(lib, db, sql[, params])SqliteIteratorUnified cursor: pass path (string) for new connection, db (Int64 from OpenDb) for existing handle, or lib (DynamicLibrary) for explicit library handle. Auto-detects form by argument types. Enumerable + IDisposable.
QueryLazy(db, sql[, params]) or QueryLazy(lib, db, sql[, params])SqliteIterator of SqliteRowSame cursor over an existing handle, but each row reads a column only when the script asks for it the win on a wide row a script reads partly. Enumerable + IDisposable.
OpenDb(path) or OpenDb(lib, path)longOpen a database and return the raw dbHandle (Int64). OpenDb(path) auto-loads sqlite3.dll; OpenDb(lib, path) uses a pre-loaded handle.
CloseDb(db)boolClose a database previously opened with OpenDb. Returns true on success. Handles are also automatically closed when the interpreter is reset or disposed.
CreateFunction(db, name, argCount, deterministic, callback) or CreateFunction(lib, db, name, argCount, deterministic, callback)boolRegister a script function as a SQLite UDF. Pass 0 for lib to auto-resolve. Use UnregisterFunctions(db) to free the callback handle.
Query<T>(path|db|lib, path|db, sql[, params])SqliteMappingIteratorTyped cursor (each row mapped to a T class instance). Auto-detects form by argument types (same as Query). Enumerable + IDisposable.
Query<T, V>(path|db|lib, path|db, sql[, params])VFlexible return (List, Dict, instance, scalar). Same source detection.
UnregisterFunctions(db)boolUnregister all UDFs on a connection
BulkInsert(lib, db, table, colNames, rows[, batchSize[, useTransaction]])longBulk INSERT: script-list path (prepared statement bind); binary path when colNames is byte[]
SerializeRows(colNames, rows)byte[]Serializes script rows to binary format accepted by BulkInsert
CsvImport(lib, db, table, csvPath, batchSize, hasHeader, colNames)longStream CSV file into table, auto-detect delimiter
LoadExtensions(lib, db, firstExt, ...)boolLoad SQLite extension DLLs (FTS5, math, etc.)
AttachDatabase(lib, db, path, alias)boolAttach another database file for cross-DB queries
DetachDatabase(lib, db, alias)boolDetach a previously attached database

The script functions SQL can call

The six slc_* functions are a second way into this engine. The methods above let a SCRIPT talk to a database; these let a DATABASE talk to a script, because ScriptLangCore.dll is itself a SQLite loadable extension. From then on SQL has real logic in it: an expression, an aggregate, a whole set, or a file's own functions, all written in this language and all running on one interpreter per connection.

The purpose is worth stating plainly, because a REPL session is where it pays off first. The sqlite3 shell is a REPL for data, and with the DLL loaded its expressions are no longer limited to what SQLite can spell: a WHERE clause can call a function you wrote, an aggregate can be any fold, and a set can be mapped with one script expression instead of a chain of CASE. Nothing needs to be installed, because the DLL is the engine itself, and each connection gets its own interpreter, so what a script declared stays callable for as long as the connection lives.

Loading the DLL from the command-line shell. From a sqlite3 session the load is one line, and the entry point is init:
sqlite> .load ./ScriptLangCore init
sqlite> select slc_eval_scalar('a0 * 2', 21);
42
The path is the DLL without its .dll suffix, and SQLite finds the file itself. The entry point is exported under three names: init (the short one), sqlite3_scriptlangcore_init (the name SQLite DERIVES from the file, i.e. the basename without its extension, without a leading lib, lowercased, so a bare .load ./ScriptLangCore works too) and init_sta (the same, and it makes the calling thread the main STA so a script can drive COM; see the note under the table). If the shell answers no such function the entry point was not found: spell it, as .load ./ScriptLangCore init. It can also be done without the REPL, one shot per invocation: sqlite3 my.db ".load ./ScriptLangCore init" "select slc_eval_scalar('a0 * 2', 21);", and as a SQL statement with select load_extension('./ScriptLangCore', 'init');. The statement form needs extension loading enabled in the host (the shell has it on; an application asks for it with SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION before opening the connection it will use), while .load is the shell's own door and needs nothing. The floor is SQLite 3.31, an older host is refused by name, and the functions are registered DIRECTONLY, which is why a schema cannot carry a reference to them (see the note under the examples). The sqlite> in these examples is the shell's prompt and not SQL: from SQLite 3.54 the shell shows its application and version there instead, and its continuation prompt spells the characters still needed to close a statement, which the embedding howto covers with the two lines that pin the classic pair.

A script can load the same DLL for a connection it already holds, which is the same registration done from this side: Sqlite.LoadExtensions(lib, db, "<path>/ScriptLangCore.dll"). Then a scalar question can be answered from inside the connection: Sqlite.Query(lib, db, "select slc_eval_scalar('a0 * 2', 21)").

A script that drives COM needs an STA thread, and the shell's own thread is not one (Windows reports it as an implicit MTA, because the shell never initialized COM), so the plain entry point answers COM Automation requires an STA thread for it. That thread never chose MTA, so it can still become the main STA, and the third entry point does exactly that before the session exists: .load ./ScriptLangCore init_sta, also select load_extension('./ScriptLangCore', 'init_sta'). It is the host's thread, so the cost is stated: after an init_sta load that thread is the main STA for the rest of its life, and a host that later asks for MTA on it gets RPC_E_CHANGED_MODE. A thread whose host did choose MTA cannot be converted, and init_sta refuses it by name.

print goes nowhere through this door, so a payload reports through Console.Error. The extension gives its session a sink that discards text (TextWriter.Null), because a host's console is not the script's to write on: a SELECT that evaluates print(...) once per row would flood the shell. The door for a diagnostic is therefore stderr, which is where the engine's own log already goes: Console.Error.WriteLine("phase 2: " + rows + " rows"); shows up in the shell, while print(...) is dropped. A payload that has to answer with data returns it (slc_file, slc_eval) rather than printing it, which is why assets/language/samples/sqlite/excel_matrix_roundtrip.slc builds one object holding its verdict and its matrix.

FunctionAnswerWhat it is for
slc_eval(code, a0, ...)TEXT, the run's result as JSONThe one that carries a failure: the JSON holds HasError, ErrorMessage, ReturnValue, ExitCode and the position, so a failing row is a value rather than a broken query.
slc_eval_scalar(code, a0)The value, as a native SQL valueA number, text, blob or NULL that a WHERE, an ORDER BY or a sum() can use directly. A failing run is a SQL error here, since a bare value has nowhere to carry the failure.
slc_agg(code, value)The fold's final stateAny aggregate in one function: a0 is the running state (NULL on the first row) and a1 the row's value, and the expression's answer becomes the new state.
slc_map(code, rows)TEXT, a JSON array of valuesA whole set in one call, for a document you already hold: rows is a JSON array, and an element that is itself an array supplies the arguments in order.
slc_map_agg(code, a0, ...)TEXT, a JSON array of valuesThe same answers with the rows coming from a query, arguments spelled as slc_eval spells them.
slc_file(path)TEXT, the run's result as JSONRuns a script FILE in the connection's interpreter, once per call: the file is re-read, re-parsed and re-compiled every time, so it is a LOADER rather than a per-row door (about 165 KB of allocation for a 120-byte file and 12 MB for a 7 KB file of 200 functions, against about 18 KB for calling a function the file already declared). Afterwards its functions are callable from the other seven, which is how a schema carries its logic instead of one expression. What the file returns is its top-level return <value>, or else the value of its last top-level expression statement, so a file that ends in Build(); answers {"HasError":false,"ExitCode":0,"ReturnValue":{...}} and one that only declares things answers no ReturnValue member at all. A path holding a compiled bundle is run too, decided by the file's content rather than by its extension: a program bundle (--compile, with or without --source=strip) answers exactly what its source answers, and a library blob, which names no entry, is refused naming import and .loadslcbc.
-- slc_eval: the whole run as JSON, which is the form that carries the failure fields select slc_eval('a0 + a1', 2, 3); -- {"HasError":false,"ExitCode":0,"ReturnValue":5} select json_extract(slc_eval('{n: a0 * 2}', 7), '$.ReturnValue.n'); -- 14 (the run answered a document) -- slc_eval_scalar: one value per row, so a script can decide what a WHERE or an ORDER BY keeps select slc_eval_scalar('a0 * 2', 21); -- 42 select n from t where slc_eval_scalar('a0 > 2 && a0 < 5', n); -- the rows the script accepts -- slc_agg: any aggregate in one expression, a0 being the running state and a1 the row with t(n) as (values (1),(2),(3),(4),(5)) select slc_agg('(a0 ?? 0) + a1', n) from t; -- 15 (a sum) select slc_agg('(a0 ?? 0) + a1 * a1', n) from t; -- 55 (a sum of squares) -- slc_map: a whole set in one call, for a document you already hold select slc_map('a0 * a0', '[1,2,3]'); -- [1,4,9] select slc_map('a0 + a1', '[[1,10],[2,20]]'); -- [11,22] (an array row supplies a0 and a1) -- slc_map_agg: the same answers with the rows coming from a query, and no JSON in the middle with t(a,b) as (values (1,10),(2,20)) select slc_map_agg('a0 + a1', a, b) from t; -- [11,22] select key, value from json_each((select slc_map_agg('a0 + a1', a, b) from t)); -- 0|11 and 1|22: rows back out -- slc_file: a whole script, so its functions stay callable for the connection select json_extract(slc_file('D:/rules/grades.slc'), '$.HasError'); -- 0 select slc_eval_scalar('Grade(a0)', score) from results; -- the file's own Grade(), per row -- slc_avro_schema / slc_avro_json: a stored Avro container, by its own schema and as pure JSON select json_extract(slc_avro_json(data), '$[1].Name') from files; -- one record's field, out of the BLOB select json_extract(slc_avro_schema(data), '$.name') from files; -- the record name the file declares select value from json_each(slc_avro_json(data)); -- one ROW per stored record

A file's ReturnValue is what the file answers: its top-level return <value> when it has one, because a top-level return ends the run and hands its value over, and otherwise its last top-level expression statement. So return Build(); and a trailing Build(); answer the same thing, and json_extract(slc_file('…'), '$.ReturnValue.X') reads a field of the object either way, while a file that only declares classes and functions answers {"HasError":false,"ExitCode":0} with no ReturnValue member. A value of null is the same: the member is absent rather than null. Any value travels, a class instance included, whose fields become the document, which is how a script hands back a whole report (return log;) and a query reads it with json_each. The returned value is not the exit code: read ExitCode for that, and exitcode = N (or exit(N)) is what sets it.

From a SCRIPT the same run is RunScript(path, true), whose .ReturnValue is that identical value and whose Json.Serialize(result) is byte for byte the text slc_file answers; the one difference is scope, since RunScript runs in an isolated interpreter by default (pass preserveContext: true when the caller wants the file's functions to stay callable, which is what slc_file does for the connection).

Each function declares the arity it really has, which is what pragma_function_list reports and what makes SQLite refuse a wrong argument count itself, at prepare time, naming the function (wrong number of arguments to function slc_map()), where an extra argument used to be accepted and silently ignored. Six are fixed (slc_file 1, slc_map 2, slc_agg 2, slc_eval_scalar 2, slc_avro_schema 1, slc_avro_json 1) and two are variadic, reported as -1 because the count is the caller's: slc_eval reads a0..aN and slc_map_agg sees every row's a0..aN, and both then refuse a call that supplies no code at all. A NULL code (or a NULL path) answers NULL rather than an error.

The eight are registered SQLITE_DIRECTONLY, so a schema cannot use them: an expression index, a CHECK constraint and a generated column are refused when you create them, while a VIEW, a TRIGGER and a DEFAULT clause are created and then refused with unsafe use of slc_eval_scalar() when something reaches them. That is the property the flag exists for: a database that arrives from elsewhere must not be able to carry a schema that runs script code with the host's permissions, so such a reference simply fails when used, and without the DLL loaded a statement naming one is unknown function. The functions also run on the connection's own interpreter, so what a script declares stays callable for the connection's lifetime. docs/embed/howto.html has the rest: the entry point, threads, what a script's print does, and what a row costs.

SQL parameter binding

All cursor methods accept SQL with ? placeholders. Parameters can be passed as individual arguments (via params Array) or as an array literal [val1, val2]. The underlying sqlite3_bind_* functions handle type dispatch: integers → sqlite3_bind_int64, floats → sqlite3_bind_double, strings → sqlite3_bind_text, null → sqlite3_bind_null, byte arrays → sqlite3_bind_blob.

Bulk insert PRAGMAs

BulkInsert applies optimization PRAGMAs before inserting and restores them to defaults afterwards regardless of the useTransaction flag (script-list path). The optimization PRAGMAs are synchronous=OFF, temp_store=MEMORY, foreign_keys=OFF, cache_size=-80000. They are restored to synchronous=NORMAL, temp_store=DEFAULT, foreign_keys=ON, cache_size=-2000 after completion. Disabling foreign keys during bulk inserts eliminates per-row FK constraint checks, which can dramatically speed up inserts on tables with foreign key relationships. The script-list path also uses savepoints (SAVEPOINT/ROLLBACK TO/RELEASE) for partial rollback safety when useTransaction=true. The binary path always uses a single transaction with savepoints.

Blob columns

A BLOB column arrives as a byte[]: Sqlite.Query, the typed mapping and the cursors all take the copy route, so the bytes stay valid for as long as the script holds them. The binding also has a zero-copy route, internal only: SqliteBlobManager is a MemoryManager<byte> over the pointer sqlite3_column_blob returns, handed out as ReadOnlyMemory<byte> by SqliteIterator.ReadBlobMemory(stmt, iCol) and SqliteNative.ReadBlobValueMemory(valPtr). Neither is exposed to scripts, and that is deliberate SQLite invalidates that pointer on the next sqlite3_step(), on a reset or finalize, and on a type conversion of the same column (reading it as text, for instance), a lifetime only the caller knows when it will end. If a script ever needs to avoid the copy, the shape that survives stepping is SQLite's incremental blob API (sqlite3_blob_open / blob_read / blob_close), which holds a handle per blob instead of a pointer per row not currently bound here.

Wide rows: read the columns you need

The row objects Sqlite.Query yields materialise every column of every row, so a SELECT * over a wide table is dominated by columns the script never reads. Measured on an 80-column table (500 rows, 100 iterations, AOT, :memory:, best of two): SELECT * takes 685 ms against 68 ms for five named columns and 34 ms for one a 20× spread that is per-column materialisation, not sqlite3_step cost, which is why it is invisible on narrow tables (the 4-column benchmark below reads all of its columns for the same time as it reads none of them in the lazy case). Three ways to stay on the fast side: name the columns (SELECT c1, c2 …), map into a small class with Sqlite.Query<T> whose fields are only the ones the query returns, or when the query is written by someone else and SELECT * is what you have use Sqlite.QueryLazy.

Sqlite.QueryLazy(db, sql[, params]) yields SqliteRow objects that read a column when the script asks for it, copy it, and cache it for that row. On the same 80-column table, reading one column of a SELECT * through the lazy row costs 123 ms against 685 ms for the eager path 5.6×, 18% of the eager reading and the ceiling, naming the column so the query returns nothing else, is 30 ms (4%). It is ahead on narrower selections too, for the same reason it skips the per-row dictionary: SELECT c1…c5 through the lazy row measured 49 ms against 68 ms eager. What it uniquely rescues is the SELECT * nobody wants to rewrite. A row that outlives its cursor position (kept past the next MoveNext, or past Dispose) throws a clear error instead of reading native memory the statement has already released; copy what you need inside the loop.

The wide-row figures come from one interleaved run on the AOT build (best of two), so the eager and lazy numbers in this section are directly comparable; the eager path has not changed, so an earlier revision's higher spread (534/48/18 ms, a 30× reading of the same effect) is the same effect measured on another day, not a different code path. The step-0 probe recorded in docs/reasonix/plans/2026-09-12-sqlite-wide-row-plan.md also settled a design question: positional storage is only ~3% cheaper than the eager dictionary row (652 ms vs 672 ms for a whole-row read), because the cost is per-column read-and-copy, not per-row dictionary overhead so QueryLazy needs no separate "eager positional" mode, and row.Values() covers "give me the whole row". assets/language/repl/data/sqlite_lazy.slc is the tracked suite for the behaviour values, accessors, lifetime guard and asserts structure rather than timing, so it stays portable across builds.


Performance measured on the AOT build, bytecode VM ON vs OFF (500-row table in :memory:, 100 iterations per read = 50 000 rows per read phase; 10 000 rows per write):

OperationVM onVM offThroughput (VM on)Throughput (VM off)Notes
Write 10k rows, INSERT per row (text SQL)110–117 ms491–492 ms~85k–91k rows/s~20k rows/sOne sqlite3_prepare_v2 a full parse of the same statement per row, in one transaction, driven by a script helper call. That call is the VM-sensitive part; the SQL work is not (see the note)
Write 10k rows, Sqlite.BulkInsert12–13 ms12–13 ms~770k–830k rows/s~770k–830k rows/sOne prepared INSERT … (?1..?N) reused per row reset, clear_bindings, binds, step in one transaction. ~7× the row above, and VM-insensitive: the binds and the step dominate
Read, lazy (foreach over cursor)100–101 ms99–109 ms~495k–500k rows/s~460k–505k rows/sNo materialization. The few-% mode difference is inside the run-to-run spread
Read, lazy row (QueryLazy, 1 column read)93–99 ms95–105 ms~505k–538k rows/s~476k–526k rows/sOne column read per row through a SqliteRow. On this 4-column table it lands in the same band as the rows around it the lazy row pays off on wide rows (123 ms vs 685 ms over 80 columns, in the section above), and a cheaper reading here would mean it was not doing the work asked of it
Read, materialized List<T>95–98 ms89–102 ms~510k–526k rows/s~490k–560k rows/sPer-row ClassMapping through a cached map
Read, materialized Dictionary102–103 ms99–106 ms~485k–490k rows/s~470k–505k rows/sAs List, plus the Dictionary insert

Measured with assets/language/repl/bench/crash_memory_bench_sqlite.slc phase 1a is the library handle's resolved-export lists and their JSON, phase 0 the per-row write loop, phase 8 the read benchmarks, 8b the write-path comparison and 9 the heap readout, all in that one file, so every row and figure below can be reproduced by running it (its timing, throughput and heap readings come from the shared assets/language/repl/bench/_bench.inc module, so they are one implementation rather than three); VmSetEnabled(false) disables the bytecode VM to produce the "VM off" column. Ranges are over the passes measured, at least three per row and per mode, because a range's lower end against a single reading can look like a regression that is not there. Run-to-run spread reaches ~6%, so anything below that is not a result. Where the write time goes: the per-row row's ~4.6× VM gap is the script-side helper call, not the SQL the same inserts written without the helper call phase 8b's inline per-row loop measured 90–94 ms in both modes (VM on 91–92, tree 90–94), so the VM-sensitive work is the call, just as the few-% spread between modes on the reads says the SQL work is not. The real per-row cost is the parse: removing it, as Sqlite.BulkInsert does by preparing the INSERT once, takes 10k rows from ~90 ms to 12–13 ms. The caller transaction is worth ~2.2× (28–29 ms without it). The binary path (SerializeRows + BulkInsert, one multi-row INSERT per batch) measured 19–21 ms real, but not faster than the script-list BulkInsert, so it is not the one to reach for on this shape. Every write path is VM-insensitive; a write that looks VM-bound is a script-side loop, not SQLite.

On the read side the rows vary only a few % between modes, which is why they are reported as VM-insensitive no read row was faster on the tree than on the VM by more than one drift step. The reads land within a few ms of each other in both modes because the native sqlite3_step plus the per-row work dominates, and on a narrow table QueryLazy is simply one of those reads: its win is on wide rows 123 ms against 685 ms for an 80-column SELECT * whose script reads one column which is why it exists at all. Memory, produced by the suite's own phase 9 rather than read by hand: 0.56 MB managed heap after a forced collection before the workload starts, 14.4–14.5 MB at the end in VM-on mode against 7.4–7.5 MB in tree mode, and 1.52 MB after a forced collection in both modes the same live set either way, so that end-of-run gap is memory not yet collected rather than memory retained, and a full collection releases ~89% of the VM-on end reading and ~80% of the tree one. (The end reading is higher than an earlier revision of this table carried: phase 8b allocates ~10k rows per repetition, which is exactly why the after-collection figure is the one that means something.) What remains is engine state that survives a full collection, and it is not the caches a script can clear: ClearPureCache() and VmReset() leave the reading unchanged (both measured after the run), so the pure-memo and compiled-function caches are not it. The working set ends at 31,629,312–31,662,080 bytes on the VM and 30,683,136–31,051,776 on the tree 30.2–30.3 MB and 29.3–29.6 MB in the same unit as the heap lines above, the suite printing the working set in raw bytes not the 97 MB an earlier revision of this row reported; the smaller peak and the ~100× faster reads point at one cause a mapping path that no longer reflects per row. The AOT build uses OptimizationPreference=Speed + IlcInstructionSet=native.

Sqlite.OpenDb Open a database and return the raw dbHandle

Opens a SQLite database and returns the raw handle as an Int64. Two calling forms are supported:

  • OpenDb(path) auto-loads sqlite3.dll from standard library paths.
  • OpenDb(lib, path) uses a pre-loaded library handle obtained via LoadLibrary("sqlite3.dll") (for custom DLL paths).

The handle can be used with Query and CreateFunction to share the same connection. It is automatically tracked for cleanup when the interpreter is disposed no explicit sqlite3_close needed from script code.

var db = Sqlite.OpenDb(":memory:"); // auto-loads sqlite3.dll var lib = LoadLibrary("tools/sqlite3.dll"); // custom path var db2 = Sqlite.OpenDb(lib, "/path/to/file.db");
// Open in-memory DB, register a UDF, iterate with kv.Key / kv.Value var db = Sqlite.OpenDb(":memory:"); // auto-loads sqlite3.dll Sqlite.CreateFunction(db, "doubleVal", 1, true, fun (int x) { return x * 2; }); foreach (var kv in Sqlite.Query(db, "SELECT doubleVal(21)")) print(kv.Key + " = " + kv.Value); // "doubleVal(21) = 42" Sqlite.CloseDb(db); // optional auto-closed on reset/dispose
Note: sqlite3_open is a lazy operation an invalid path won't fail until the first SQL operation. Use :memory: for temporary databases. The returned value is a native Int64 handle, treated as a number in script.
Calling convention: When calling Query(lib, db, sql) or CreateFunction(lib, db, ...), Query(db, sql, ...) and CreateFunction(db, name, ...) auto-resolve the lib. Query(lib, db, sql, ...) and CreateFunction(lib, db, name, ...) use an explicit DynamicLibrary handle.
Sqlite.CloseDb Close a database previously opened with OpenDb

Closes a SQLite database handle that was obtained from Sqlite.OpenDb. Returns true on success, false if the handle is already closed or invalid. Uses sqlite3_close_v2 internally (with fallback to sqlite3_close for older SQLite versions).

Calling CloseDb is optional for :memory: databases and short-lived scripts handles are automatically closed when the interpreter is reset (.reset all) or disposed. For long-running scripts that open many databases, explicit close prevents resource exhaustion.

Sqlite.CloseDb(db);
var db = Sqlite.OpenDb("mydb.sqlite"); Sqlite.CloseDb(db); // explicit close
Sqlite.Query Open a lazy cursor over a SQL query

Executes a SQL query and returns an IEnumerable that yields each row as a dictionary with string keys and object? values. Four calling forms are supported auto-detected by argument types:

  • Query(path, sql[, params]) opens a new connection. Auto-loads sqlite3.dll.
  • Query(db, sql[, params]) reuses an existing handle from OpenDb(). Auto-resolves lib.
  • Query(lib, path, sql[, params]) new connection with explicit library handle.
  • Query(lib, db, sql[, params]) reuses existing handle with explicit library handle.

Important: Forms that open a new connection (Query(path, sql), Query(lib, path, sql)) do not have access to UDFs registered via CreateFunction. Use Query(db, sql) to share the same connection.

Row iteration: Each row supports foreach(var kv in row) access the column name via kv.Key and the cell value via kv.Value. Alternatives: row["colName"] or row[0].

// Auto-load + new connection, iterate with kv.Key / kv.Value foreach (var kv in Sqlite.Query(":memory:", "SELECT 1 AS x")) print(kv.Key + " = " + kv.Value); // "x = 1" // Reuse existing db handle (UDFs available) var db = Sqlite.OpenDb(":memory:"); Sqlite.CreateFunction(db, "doubleVal", 1, true, fun (int x) { return x * 2; }); foreach (var kv in Sqlite.Query(db, "SELECT doubleVal(21)")) print(kv.Key + " = " + kv.Value); // "doubleVal(21) = 42" Sqlite.CloseDb(db); // close when done // Explicit library handle + path var lib = LoadLibrary("sqlite3.dll"); foreach (var kv in Sqlite.Query(lib, ":memory:", "SELECT 1 AS x")) print(kv.Key + " = " + kv.Value);
Sqlite.QueryLazy Cursor whose rows read a column only when asked

Same SQL execution as Sqlite.Query, over an existing handle, but the rows it yields are SqliteRow objects that materialise a column on access: the value is read from the native statement, copied, and cached for that row. A script that reads three of eighty columns pays for three.

Two calling forms both need a handle from OpenDb():

  • QueryLazy(db, sql[, params]) existing handle, library auto-resolved.
  • QueryLazy(lib, db, sql[, params]) existing handle with an explicit library handle.

Lifetime: a row is valid only while it is the cursor's current row. Once the cursor steps again or is Disposed every read on the old row throws ("This SQLite row is no longer live…") instead of returning data from a statement position that has already moved. Copy what you need inside the loop; collecting rows for later use is what the eager Query path is for.

Row access: by name or by ordinal

A SqliteRow is a read-only dictionary with the same two access forms the eager rows have: by name (r["c1"], case-insensitive) or by ordinal (r[0], the position in the SELECT list, 0-based). Both resolve to the same slot, so they share the per-row cache and the same lifetime rule mixing the two in one loop is fine. Assigning to a column throws.

MemberReturnsNotes
r["c1"]objectBy column name, case-insensitive. An unknown name throws Column 'x' not found in the query result.
r[0]objectBy ordinal, in Keys() order. Negative, or past the last column, throws Column index N is out of range: the row has M column(s).
r.GetValue(i)objectThe ordinal form as a method.
r.GetKey(i)stringThe column name at that ordinal.
r.CountintHow many columns the query returned.
r.Keys()string[]Column names in query order so r[i] == r[r.Keys()[i]].
r.Values()object[]The whole row, positionally. Reads (and caches) every column on the first call.
r.ContainsKey(k)boolTakes a column name or an ordinal.
foreach (var kv in r)KeyValuePairName/value pairs, in query order.

Any of these reads is what triggers the native read and only for the column asked for. A name and its ordinal are the same slot, so r[2] after r["c2"] copies nothing twice.

var db = Sqlite.OpenDb(":memory:"); // ... fill a wide table ... // By name reads only c1 and c7, whatever else SELECT * returns foreach (var r in Sqlite.QueryLazy(db, "SELECT * FROM wide")) print(r["c1"] + " / " + r["c7"]); // The same columns by ordinal 0-based position in the SELECT list foreach (var r in Sqlite.QueryLazy(db, "SELECT id, c1, c2, n FROM wide")) { print(r[0] + " | " + r[1] + " | " + r[3]); // id | c1 | n print(r[2] == r["c2"]); // True same slot } // The name at a position, or the whole row positionally foreach (var r in Sqlite.QueryLazy(db, "SELECT * FROM wide")) { print(r.GetKey(2) + " = " + r.GetValue(2)); var vals = r.Values(); print(vals[0]); }

An ordinal only means something for that query: it follows the columns the SELECT actually returned, in order. r.Keys() reports that order, and GetKey(i) turns a position back into a name the pair to reach for when the query is SELECT * and the column order is not yours to fix.

When not to use it: for a narrow row, or when you keep every row, plain Query is the simpler call same values, no lifetime rule to respect. On an 80-column table, reading one column of SELECT * through QueryLazy measured 123 ms against 685 ms for the eager path (5.6×); naming the column in the SQL (SELECT c1) stays the fastest at 30 ms.
Sqlite.Query<T> / Sqlite.Query<T, V> Typed cursor maps rows to class instances

Two typed overloads same source detection as untuned Query:

  • Query<T>(...) typed cursor (1 type arg). Each row is mapped to a T class instance. Call it from sqlite.inc wrappers as db.Query<Person>(sql).
  • Query<T, V>(...) flexible return (2 type args). V can be List<T>, Dictionary<K,V>, a class name, or a scalar type. Also available as db.Query<Person, List<Person>>(sql).
class Person { public int Id { get; set; } public string Name { get; set; } } // Typed cursor foreach (var p in Sqlite.Query<Person>(lib, db, "SELECT * FROM people")) print(p.Id + " " + p.Name); // Flexible return var list = Sqlite.Query<Person, List<Person>>(lib, db, "SELECT * FROM people"); var cnt = Sqlite.Query<Person, int>(lib, db, "SELECT COUNT(*) FROM people");

The second type argument V controls the return shape:

VReturns
T (a class)Single ClassInstance (first row only)
List<T>List<T> with all rows
Dictionary<K, T>Dictionary keyed by first column
scalar (int, string, ...)First column of first row, coerced to V
Iterator types: Query returns a SqliteIterator (row cursor) and Query<T> returns a SqliteMappingIterator (maps each row to a class instance). Both are enumerable (foreach), implement IDisposable (.Dispose() releases the statement), and are usable with is / typeof / as under these exact names.
Sqlite.BulkInsert Multi-row INSERT with parameterized prepared statements

Multi-row INSERT using parameterized prepared statements with ?1..?N placeholders. Prepares the INSERT once, then reuses it per row via sqlite3_reset + sqlite3_clear_bindings + sqlite3_bind_*. By default wraps the operation in BEGIN TRANSACTION/COMMIT with savepoints. Pass false as the 7th argument to skip the transaction. Returns the number of rows inserted.

Signature (script-list path)

Sqlite.BulkInsert(lib, db, "table", colNames, rows[, batchSize[, useTransaction]])
  • colNames string[], List<string>, or any IList
  • rows object[] (each element: object[] or IList of values), List<T>, or script struct/class instances (fields extracted by name)
  • batchSize rows per batch (default: 1000)
  • useTransaction bool, default true

Signature (binary path)

Sqlite.BulkInsert(lib, db, "table", byteData[, batchSize])

Auto-detected when args[3] is byte[]. Uses multi-row VALUES SQL internally.

// Full form with explicit lib and db handles var lib = LoadLibrary("sqlite3.dll"); var db = Sqlite.OpenDb(lib, "test.db"); var colList = ["Name", "Value", "Active"]; struct Row { public string Name; public string Value; public int Active; } var rowList = new List<Row>(); rowList.Add(new Row("a", "hello", 1)); rowList.Add(new Row("b", "world", 1)); var inserted = Sqlite.BulkInsert(lib, db, "my_table", colList, rowList, 1000); print("Inserted " + inserted + " rows"); Sqlite.CloseDb(db); FreeLibrary(lib);

SQL injection safety: Values are never concatenated into SQL strings. All data is passed via sqlite3_bind_* special characters, quotes, and null bytes in column values are handled safely by SQLite's binding API.

Sqlite.BulkInsert (binary path) Multi-row INSERT from a pre-serialized byte[] auto-detected by BulkInsert

Takes a pre-serialized byte[] in compact binary format and builds multi-row INSERT INTO t (cols) VALUES (v1),(v2),... SQL strings. BulkInsert auto-detects byte[] at args[3] and routes to this path (instead of the prepared-statement path used for script lists). Useful when data originates from host C# code that can produce the binary format directly, avoiding script-object allocation entirely. Wraps the operation in BEGIN IMMEDIATE TRANSACTION / COMMIT with savepoints, applies optimization PRAGMAs before and restores defaults after. Returns the number of rows inserted.

Binary format

[4B colCount][4B rowCount]
for each col: [4B nameLen][nameBytes] (UTF-8, not null-terminated)
for each row, each col: [1B tag][value]
  tag=0: no value bytes (NULL)
  tag=1: [8B int64]
  tag=2: [8B float64]
  tag=3: [4B strLen][strBytes] (UTF-8)

Tags 1 and 2 correspond to SQLite INTEGER and REAL. Tag 3 is TEXT (string values are single-quote-escaped). The column names in the header are used in order one per column per row is required. A column count mismatch between the header and actual row data will produce broken SQL.

SerializeRows helper

To generate the binary byte[] from script row data, use Sqlite.SerializeRows(colNames, rows) (This native C# function reads the same List<object> input as BulkInsert and serializes it to the binary format in native code no script-side allocations per row, and no hardcoded test data.

// Build rows, serialize to byte[], then bulk insert
var cols = new string[] {"id", "value", "label"};
var rows = new List<object>();
rows.Add([1, 1, "odd"]);
var byteData = Sqlite.SerializeRows(cols, rows);
Sqlite.BulkInsert(lib, db, "bulk_bytes", byteData, 1000);
(binary path) uses multi-row VALUES SQL internally it concatenates values into SQL strings rather than using prepared statements. This means string values are single-quote-escaped rather than bound via the SQLite binding API. The binary format must match the table's column types and order exactly. Use SerializeRows to generate the binary payload from script row data without hardcoding the binary format. Call BulkInsert(lib, db, table, byteData, batchSize) the method detects byte[] at args[3] and routes here automatically.
Sqlite.CsvImport Stream CSV file into a SQLite table (auto-detects delimiter)

Reads a CSV file line-by-line (streaming, no full file load), auto-detects the delimiter, and inserts rows into a SQLite table using a prepared statement with periodic batch commits. Handles quoted fields with embedded commas and escaped quotes.

The delimiter auto-detection scores candidate characters (, ; | : ^ ~ \t # @ ! % & * / \ ) by counting occurrences outside quoted regions and picks the one with the most hits. Falls back to comma if none scores ≥2.

Parameter handling

colNames controls column naming:

  • If a string[] is provided, those names are used and the first CSV row is treated as data
  • If hasHeader = true (default), the first CSV row provides column names
  • If hasHeader = false and no explicit names, auto-generated col1, col2, ... are used

If the table does not exist, it is created with all columns as TEXT (SQLite flexible typing). Wraps the operation in a transaction with savepoints, applies optimization PRAGMAs before and restores defaults after. Returns the number of rows inserted, or -1 on error (fully rolled back).

Sqlite.CsvImport(lib, db, "my_table", "./data.csv", 10000, true, null);
// Auto-detect pipe delimiter, header row, create table Sqlite.CsvImport(lib, db, "csv_products", "./data.csv", 10000, true, null); // Custom column names, first row is data Sqlite.CsvImport(lib, db, "users", "./users.psv", 10000, false, ["uid", "uname"]);
Sqlite.CreateFunction Register a script function as a SQL UDF

Registers a script lambda as a callable SQL function via sqlite3_create_function. Deterministic functions can be optimized by SQLite.

// Short form auto-resolves lib from db handle var upper = fun (arg) => arg != null ? arg.ToString().ToUpper() : null; Sqlite.CreateFunction(db, "MY_UPPER", 1, true, upper); foreach (var row in Sqlite.Query(db, "SELECT MY_UPPER('hello')")) print(row["MY_UPPER('hello')"]); // HELLO
// Long form explicit library handle Sqlite.CreateFunction(lib, db, "MY_UPPER", 1, true, upper);

Return type mapping: int/short/byte/bool/char → INTEGER, long/uint/ulong → INTEGER (64-bit), float/double/decimal → REAL (decimal is converted to double), string/DateTime/TimeSpan → TEXT, byte[] → BLOB. Arguments read as long (INTEGER), double (REAL), string (TEXT), or byte[] (BLOB).

Sqlite.LoadExtensions Load SQLite extension DLLs (FTS5, math, ICU, etc.)

Loads one or more SQLite extension DLLs via sqlite3_load_extension. Automatically enables extension loading on the handle if not already enabled. Extensions like FTS5 (fts5), math functions (math), ICU, JSON1, and others can be loaded if the sqlite3.dll was compiled with extension support. Returns true on success, false if the extension file does not exist or loading fails.

Sqlite.LoadExtensions(lib, db, "./path/to/ext.dll"); Sqlite.LoadExtensions(lib, db, "./fts5.dll", "./math.dll");
Loading a non-existent extension file throws ScriptException. On Windows, the DLL must be in the same directory as sqlite3.dll or on the system PATH.
Sqlite.AttachDatabase Attach another SQLite database for cross-DB queries

Attaches another SQLite database file to the current connection under a logical alias. Once attached, tables from that database can be queried using the alias.table_name syntax. Returns true on success, false if the file does not exist or the SQL operation fails. Use AttachDatabase to join tables across databases, or to perform bulk operations across multiple files.

Sqlite.AttachDatabase(lib, db, "path/to/other.db", "other"); // Then query: SELECT * FROM other.table_name
// Cross-database join Sqlite.AttachDatabase(lib, db, "./sales.db", "sales"); foreach (var r in Sqlite.Query(db, "SELECT p.name, s.total FROM products p " + "JOIN sales.orders s ON p.id = s.product_id")) print(r["name"] + " " + r["total"]);
Sqlite.DetachDatabase Detach a previously attached database

Detaches a database previously attached via AttachDatabase. After detach, the alias.table_name syntax no longer resolves for that alias. Does not delete the database file only removes the logical attachment. Returns true on success, false if the alias does not exist.

Sqlite.DetachDatabase(lib, db, "alias");
DetachDatabase returns false if the alias does not exist no exception is thrown. Check the return value if you need to know whether the detachment succeeded.