IlluLang Standard Library Reference
This is the reference for builtins and their behavior contracts. For language syntax (types, control flow, intents), see SYNTAX. Native runtime modules (import "<name>") are listed in INTERNALS/README.
I/O
display(expr, ...) -> value- Prints arguments space-separated.
- Returns first argument, or
0when empty. input([prompt], [type]) -> string|int|float|bool- Reads a line of input from stdin, returns as string.
- Optional prompt string is printed before reading.
- Optional type parameter converts the input:
input(">> ", int),input(">> ", float),input(">> ", bool). - Type can be a bare identifier (
int) or a string ("int"). read_file(path: string) -> stringwrite_file(path: string, contents: string) -> boolappend_file(path: string, contents: string) -> boolexists(path: string) -> boollist_dir([path: string]) -> array[string]-- defaults to"."if omittedread_lines(path: string) -> array[string]-- reads file and splits into linesfile_delete(path: string) -> boolfile_copy(src: string, dst: string) -> boolfile_move(src: string, dst: string) -> boolis_dir(path: string) -> bool-- checks if path is a directoryis_file(path: string) -> bool-- checks if path is a regular file
Types / Introspection
type(value) -> string- Returns a detailed type string:
- Scalars:
"int","float","bool","string","function","none","unknown" - Arrays:
"array[int]","array[int, float]"(union of element types) - Dicts:
"dict[string, int]"(union of value types) - Matrices:
"matrix[int]" - Custom types: returns the custom type name (e.g.,
"score"forlet s: score = 42)
- Scalars:
is_int(value) -> boolis_float(value) -> boolis_bool(value) -> boolis_string(value) -> boolis_array(value) -> boolis_dict(value) -> boolis_function(value) -> boolis_matrix(value) -> boolis_none(value) -> boolis_empty(value) -> bool-- works on strings, arrays, dicts, and matricesis_strict(value_or_var) -> bool
Conversion
to_int(value) -> intto_float(value) -> floatto_string(value) -> stringto_bool(value) -> bool-- converts using truthiness rules (0/empty/none = false, everything else = true)char(code: int) -> string-- converts a Unicode code point (0..1114111) to a one-character UTF-8 stringord(str: string) -> int-- returns Unicode code point of the first character (0for empty strings)
Note: values 128..159 are Unicode C1 control code points and are usually non-printable in terminals.
Math
abs(x) -> int|floatsqrt(x) -> floatpow(base, exp) -> floatfloor(x) -> floatceil(x) -> floatround(x, [decimals]) -> float-- rounds todecimalsdecimal places (default 0)random() -> float-- automatically seeded on first callrandom_int(min, max) -> int-- random integer in[min, max]inclusive; automatically seeded on first calllog(x) -> float-- natural logarithmlog10(x) -> float-- base-10 logarithmexp(x) -> float-- e raised to the power x
Trigonometry
sin(x) -> floatcos(x) -> floattan(x) -> floatasin(x) -> floatacos(x) -> floatatan(x) -> floatatan2(y, x) -> float
Operators
| Operator | Description | Example |
|---|---|---|
+ - * |
Standard arithmetic | 2 + 3 → 5 |
/ |
Division (int when evenly divisible, float otherwise) | 10 / 2 → 5, 10 / 3 → 3.333... |
^ |
Power / exponentiation | 2 ^ 10 → 1024 |
// |
Euclidean (floor) division | 17 // 3 → 5 |
% |
Modulo (remainder) | 17 % 3 → 2 |
and |
Logical (bool) or bitwise (int/float) AND | true and false → false, 0xF and 0x3 → 3 |
or |
Logical (bool) or bitwise (int/float) OR | 0xF0 or 0x0F → 255 |
xor |
Logical (bool) or bitwise (int/float) XOR | 0xFF xor 0xFF → 0 |
not |
Logical (bool) or bitwise (int) NOT | not true → false, not 0 → -1 |
Compound Assignment
+=,-=,*=,/=,^=,//=,%=- Works on variables and indexed targets:
arr[i] += 1,d["key"] -= 5,m[r][c] *= 2
Array Arithmetic
| Expression | Result | Description |
|---|---|---|
[5] + 2 |
[5, 0, 0] |
Extend with N zeros |
[5, 8] - 1 |
[5] |
Shrink by N elements |
[7] * 2 |
[7, 7] |
Repeat array N times |
[5, 6] ^ 2 |
[[5,6]:[5,6]] |
Convert to squared matrix (var only) |
[1, 2] + [3, 4] |
[1, 2, 3, 4] |
Concatenate two arrays |
[1, 2, 3] - [2] |
[1, 3] |
Remove last occurrence of each right-hand element |
Number Bases
| Prefix | Base | Example |
|---|---|---|
0b |
Binary | 0b1010 → 10 |
0o |
Octal | 0o17 → 15 |
0x |
Hexadecimal | 0xFF → 255 |
0d |
Explicit decimal | 0d42 → 42 |
Arithmetic between same-base values preserves the base in the result. Use base() to convert or query:
base(value, target) -> int-- convert value to target base (2, 8, 10, 16). Returns the same integer with the display base set.base(value) -> int-- query the current display base of a value (returns 2, 8, 10, or 16).
display(base(255, 16)) ## 0xff
display(base(255, 2)) ## 0b11111111
display(0xFF + 0x01) ## 0x100 (base preserved)
display(base(0xFF)) ## 16
Scientific Notation
Float literals support e/E notation: 1e9, 2.5e-3, 6.022e23.
Strings
len(string|array|dict|matrix) -> intupper(s) -> stringlower(s) -> stringsubstr(s, start, [len]) -> stringtrim(s) -> stringtrim_left(s) -> string-- trims leading whitespace (alias:ltrim)trim_right(s) -> string-- trims trailing whitespace (alias:rtrim)split(s, [delim]) -> array[string]-- splits by delimiter (default" ")join(arr, [sep]) -> string-- joins with separator (default"")replace(s, from, to) -> stringstarts_with(s, prefix) -> boolends_with(s, suffix) -> boolindex_of(s, needle) -> intfind(s, needle) -> int-- alias forindex_ofrepeat(s, count) -> stringchar_at(s, index) -> string- String indexing:
s[i]returns the character at indexi(negative indices count from end)
Arrays
slice(arr, start, [end]) -> arraypush(arr, value) -> array(statement-form mutates target var)pop(arr) -> array(statement-form mutates target var)insert(arr, index, value) -> array-- inserts value at index (negative indices supported)remove_at(arr, index) -> array-- removes element at index (negative indices supported)find(arr, fn) -> value|none-- returns first element where fn returns truthy, ornonefind_index(arr, fn) -> int-- returns index of first matching element, or-1any(arr, [fn]) -> bool-- true if any element satisfies fn (without fn, checks truthiness)all(arr, [fn]) -> bool-- true if all elements satisfy fn (without fn, checks truthiness)max(arr) -> number-- also:max(a, b, ...)for scalar maxmin(arr) -> number-- also:min(a, b, ...)for scalar mincontains(arr, value) -> boolincludes(arr, value) -> bool-- alias forcontainsreverse(arr) -> array(statement-form mutates target var)sort(arr, [fn]) -> array-- O(n log n) merge sort; optional comparatorfn(a, b)returns negative/zero/positive (statement-form mutates target var)unique(arr) -> array(statement-form mutates target var)flatten(arr) -> array(statement-form mutates target var)range(end) -> array[int](equivalent torange(0, end))range(start, end, [step]) -> array[int](exclusive end)
Range operator notes (start->end[:step]):
- End is exclusive.
- Positive step follows natural direction (ascending when start < end, descending when start > end).
- Negative step returns the reverse of the corresponding positive-step range.
Dictionaries
dict() -> dictdict_get(d, key: string) -> value|0dict_set(d, key: string, value) -> dict(statement-form mutates target var)dict_has(d, key: string) -> booldict_remove(d, key: string) -> dict(statement-form mutates target var)dict_keys(d) -> array[string]dict_values(d) -> arraykeys(d) -> array[string]-- alias fordict_keysvalues(d) -> array-- alias fordict_valuesdict_merge(d1, d2) -> dict-- merges two dicts (d2 keys override d1) (alias:merge)dict_items(d) -> array[array]-- returns[[key, value], ...]pairs (aliases:entries,items)- Access:
d["key"]returns value for key - Assignment:
d["key"] = valuesets value for key - Compound assignment:
d["key"] += 1-- all compound operators supported - Value arithmetic:
d["key"] + 1works because indexing returns the stored value type
Matrices
Matrices are strict 2D grids declared with let and a required element type annotation.
is_matrix(v) -> boolmat_rows(m) -> int-- number of rowsmat_cols(m) -> int-- number of columnsmat_get(m, row, col) -> value-- get element at (row, col)mat_set(m, row, col, value)-- set element at (row, col), mutates in placemat_transpose(m) -> matrix-- returns a new transposed matrixmat_flatten(m) -> array-- returns all elements as a flat array- Row access:
m[row]-- returns a row as an array - Element access:
m[row][col]-- returns element at (row, col) - Element assignment:
m[row][col] = value-- sets element at (row, col) - Compound assignment:
m[row][col] += value-- all compound operators supported
Matrix Declaration
let m: matrix[int] = 2*3 ## 2×3, zero-initialized
let m: matrix[int] = [[1, 2]:[3, 4]] ## 2×2 literal
Functional
map(arr, fn) -> array-- applies fn to each elementfilter(arr, fn) -> array-- keeps elements where fn returns truthyreduce(arr, fn, [initial]) -> value-- accumulates via fn(acc, elem); ifinitialomitted, uses first elementforeach(arr, fn) -> 0-- calls fn(elem) for each element, returns 0enumerate(arr) -> array[array]-- returns [[0, elem0], [1, elem1], ...]zip(arr1, arr2) -> array[array]-- pairs elements: [[a0, b0], [a1, b1], ...]sum(arr) -> int|float-- sums numeric elements
String Formatting
format(fmt, ...) -> string-- printf-style formatting (alias:sprintf)%sstring,%d/%iinteger,%ffloat,%escientific,%ggeneral%x/%Xhex,%ooctal,%bbinary,%ccharacter- Width:
%10d, zero-pad:%05d, left-align:%-10s, precision:%.2f %%for literal percent
Error Handling
throw(message)-- raises a user-definederror[throw]error (works as both statement and expression)- Statement form:
throw "something went wrong" - Expression form:
throw("error message") - Caught by
try { ... } instead { ... }blocks, exposed aserrorvariable - Non-string arguments are automatically converted to strings
- References
Enum.Errors.ThrowErrorin error output assert(condition, [message])-- verifies condition is truthy- On failure, raises
error[assert]with optional message as hint - References
Enum.Errors.AssertionErrorin error output - Example:
assert(x > 0, "x must be positive")
Enum.Errors
Built-in error constant namespace. Each constant evaluates to its fully-qualified string name:
Enum.Errors.SyntaxError-- parser/syntax errorsEnum.Errors.TypeError-- type mismatch errorsEnum.Errors.DivisionByZero-- division by zeroEnum.Errors.IndexOutOfRange-- array/string index out of rangeEnum.Errors.RuntimeError-- undefined variable/function referenceEnum.Errors.ThrowError-- user-thrown errors viathrowEnum.Errors.AssertionError-- assertion failures viaassertEnum.Errors.KeyboardInterrupt-- interrupt/signal errors
Custom Enums (makenum)
Define custom enum categories with makenum Category[type] { Key: value, ... }:
makenum HttpStatus[int] { OK: 200, NotFound: 404 }-- creates an integer enummakenum Color[string] { Red: "red", Green: "green" }-- creates a string enum- Access via
Enum.Category.Member(e.g.,Enum.HttpStatus.OK->200) - Re-declaring an existing category appends only missing members; existing keys are unchanged
- Built-in categories (for example
Errors) can be extended only one member at a time
Deletion (del)
Use del to remove user-defined names or indexed entries:
del name-- deletes a user-defined variable, custom type, or custom enum categorydel name.member-- deletes a dictionary member using dot path syntaxdel Enum.Category-- deletes a user-defined enum category by namespace pathdel Enum.Category.Member-- deletes a user-defined enum member by namespace pathdel name[index]-- deletes an array element or dictionary key
Examples:
del cache-- remove variablecachedel nums[2]-- remove third array elementdel cfg["host"]-- remove dict key
Named import internals are protected. del lib["x"] is blocked, while del lib is allowed.
Built-in enum categories are protected. del Enum.Errors is blocked.
Built-in enum members are protected. del Enum.Errors.SyntaxError is blocked.
Named import internals are also protected from assignment/mutation (lib["x"] = ..., lib.x = ..., lib["x"] += ..., lib.x += ...).
JSON
json_parse(str: string) -> value-- parses a JSON string into an IlluLang value (objects become dicts, arrays become arrays). Supports all standard escapes including\b,\f, and\uXXXXUnicode escapes with proper UTF-8 encoding.json_stringify(value) -> string-- converts an IlluLang value to a JSON string
System
clock() -> float-- current time in seconds (since epoch)exit([code]) -> void-- exits the processenv_get(name: string) -> string-- get environment variableenv_set(name: string, value: string) -> bool-- set environment variableenv_list() -> dict-- returns all environment variables as a dictgetcwd() -> string-- current working directorychdir(path: string) -> bool-- change working directorysystem_exec(cmd: string) -> string-- execute shell command, returns outputinput([prompt], [type]) -> string|int|float|bool-- read a line from stdin; optional type converts resultget_args([index]) -> array[string] | string | none-- script CLI args (excluding script path). Withindex, returns one arg ornone.
Path
path_join(parts...) -> string-- joins path componentspath_dir(path: string) -> string-- directory portion of pathpath_base(path: string) -> string-- filename portion of pathpath_ext(path: string) -> string-- file extension (including dot)
Internal Libraries
Internal libraries are imported with an angle-bracket module ID inside a string literal:
import "<time>"
Detailed internal-library docs are maintained in:
INTERNALS/TIME.htmlINTERNALS/WINDOWS.html
Intent-Oriented
achieve("name", ...args) -> value|0-- dispatches intent, returns handler resultachieve_async("name", ...args) -> int-- schedules intent dispatch as a deferred task, returns task ID. Useawait(task_id)orawait_all(...)to execute.intents() -> array[string]-- list all registered intent nameshandlers(name: string) -> array[dict]-- list handlers for intent
Intent handlers support yield - yielded values are collected and returned as an array.
String Builder
sb_new() -> int-- creates a new string builder, returns a builder IDsb_append(sb: int, value) -> void-- appends value (converted to string) to the buildersb_to_string(sb: int) -> string-- returns the built stringsb_len(sb: int) -> int-- current total length in characterssb_count(sb: int) -> int-- number ofsb_appendcalls performedsb_clear(sb: int) -> void-- resets the builder (clears contents and counter)
Reference Cells
ref(value) -> int-- creates a reference cell holdingvalue, returns a cell IDderef(cell_id: int) -> value-- reads the current value of the cellref_set(cell_id: int, value) -> void-- updates the cell's value
Reference cells enable shared mutable state across closures. The cell ID is an integer that can be captured by lambdas.
Typed Array Constructors
int_array(size: int, default: int) -> array[int]-- pre-allocates an array ofsizeintsfloat_array(size: int, default: float) -> array[float]-- pre-allocates an array ofsizefloatsbool_array(size: int, default: bool) -> array[bool]-- pre-allocates an array ofsizeboolsstring_array(size: int, default: string) -> array[string]-- pre-allocates an array ofsizestrings
Async / Await
async(fn: function) -> int-- schedules a zero-argument function for execution, returns a task IDachieve_async("name", ...args) -> int-- schedules an intent dispatch as a deferred task, returns a task IDawait(task_id: int) -> value-- executes the task (if still pending) and returns its result. Works for bothasync()andachieve_async()tasks.await_all(t1: int, t2: int, ...) -> array-- executes all tasks and returns an array of results
Note: Tasks are currently executed eagerly when await or await_all is called (cooperative scheduling, not parallel threading).
Notes
- Division (
/) returns int when evenly divisible, float otherwise; use//for euclidean (floor) division. and,or,xor,notare dual-purpose: logical on booleans, bitwise on integers/floats.