Library Reference​

Full API signatures: arguments, defaults, results, effects, and availability for builtins, standard-library functions, and the standalone runner.

Builtin methods​

Taught in Containers & Strings. One registry serves both backends, so the lists below are the same on each. A method changes its receiver in place; the array::, map:: or string:: function of the same name returns a copy (the pairs).

Arrays (35)​

kindmethods
observerssize length empty front first back last index_of contains has
call back per elementreduce for_each find find_index some every
returns a stringjoin
change in place, return nothingpush clear insert resize assign fill reserve sort reverse slice filter map concat append
change in place, return what they tookpop (the element) remove erase (whether there was one) remove_if (the count)
OnRule
a.filter(f)Keeps the elements f accepts in a itself and returns nothing: auto b = a.filter(f); is an error (the text).
remove_ifDrops the elements its predicate accepts.
popOn an empty array raises a catchable error.
callbacksReceive the element, or the element and its index for a two-parameter callback. A T& element parameter is the element itself.
a.map(f)Keeps a's element type (results convert into it).
array::mapReturns an array<T> when its callback declares T.
find, find_indexA copy or null; an index or -1.
reduce(f)Without an initial value raises on an empty array.
insert(i, v)Takes i from 0 to size().
typed array (array<int>)Checks every store against its element type.
array<var>, a literal with no spelled element typeHolds anything.

Maps (14)​

kindmethods
observerssize length empty contains has get keys values to_array
change in place, return nothingclear filter
change in place, return what they tookerase remove (whether the key was there) remove_if (the count)
OnRule
m[key] = vInserts or overwrites.
reading a missing keyRaises (Key "k" not found in map) and never inserts, on every map: a plain read, a compound or increment, a reference bound to the entry.
contains(key)Whether the key is there.
get(key)The value, or null for a missing key.
get(key, default)The value, or the explicit fallback.
filterThe predicate takes (key, value); keeps the accepted entries. map::filter(m, f) returns a new map.
keysOrdered (key order). Any script value can be a key: the total ordering of <=> guarantees it.
declared key typeEnforced on stores (map<string,int> m; m[5] = 1 raises). Keys never coerce.

Strings (56: 38 reading, 18 in place)​

kindmethods
reading (leave the string alone)size length byte_size empty at front back substr find rfind find_first_of find_last_of find_first_not_of find_last_not_of contains starts_with ends_with count compare to_int to_float split explode lines partition is_digit is_alpha is_alnum is_space is_upper is_lower utf8_chars utf8_length is_valid_utf8 code to_utf8 to_bytes reader
in-place mutators (change the receiver, return nothing)append to_lower to_upper trim trim_left trim_right pad_left pad_right pad_center replace replace_first replace_last insert erase remove_prefix remove_suffix reverse repeat
OnRule
s[i]Indexes bytes and returns a char, which promotes to an unsigned int (0..255) in numeric contexts.
byte idiomss[i] + 0 reads a byte value, s[i] - '0' is the digit-parse shape, s[i] == 0x1A is a byte test.
s.at(i)The same char, a negative i counting from the end. On a utf8_string, u.at(i) returns character i as text.
s[i] = cReplaces byte i.
s[i] = textReplaces byte i with the whole text. s[i] += text joins the char with the text, then stores it.
a char beside a stringCompares and joins as its one-character text (s[i] == "x", s + 'c').
u[i] on a utf8_stringReads and replaces character i.
cast<char>(n), to_char(n)Mint a byte, range-checked 0..255. out += cast<char>(b) is the binary-writer shape.
\xNNA byte in a quoted or backtick string: exactly two hex digits. "\x00" embeds a real NUL.
R"(text)", R"delim(text)delim"A raw string: no escapes, a line ending inside as one \n. The delimiter is up to 16 characters, none a space, parenthesis, backslash or quote.
findReturns -1 when absent.
split()Splits on whitespace and drops empty pieces; split(string::whitespace) is the same.
split(sep)Keeps empties. split("") splits into characters. explode is its synonym.
a mutator's resultCannot be used: auto upper = name.to_upper(); and the chain s.trim().to_lower() are errors (the text).
a changed copyBuild with + (which never mutates), or call the string:: function of the same name: string::to_upper(s) returns a new string.
to_utf8A utf8_string.
to_bytes([offset], [count])An array<uint8>.
reader()A binary::reader (its calls).
a utf8_stringAnswers the same method names in characters, except to_utf8.

Smart pointers​

typemethods
shared_ptr (5)reset use_count cpp_ref_count unique same_as
weak_ptr (4)lock expired reset same_as

Synonyms​

The same arguments, result and in-place behavior under either name.

OnThe same method
array, map, stringsize = length
array, mapcontains = has; remove = erase
arrayfront = first; back = last; concat = append
stringsplit = explode

In place or a copy​

Using an in-place method's result is an error (the text). Every copying function is [[nodiscard]]. The rules: In place or a copy.

In place, returns nothingReturns a copy
xs.append(other), xs.concat(other)array::append(xs, other), array::concat(xs, other)
xs.filter(f)array::filter(xs, f)
xs.map(f)array::map(xs, f)
xs.resize(n), xs.resize(n, v), xs.fill(v)array::resize(xs, n), array::resize(xs, n, v), array::fill(xs, v)
xs.slice(start, end)array::slice(xs, start, end)
xs.sort(), xs.sort(f)array::sort(xs), array::sort(xs, f)
xs.reverse()array::reverse(xs)
m.filter(f)map::filter(m, f)
s.append(text)string::append(s, text)
s.trim()string::trim(s)
s.to_lower(), s.to_upper()string::to_lower(s), string::to_upper(s)
s.replace(from, to)string::replace(s, from, to)
s.repeat(n)string::repeat(s, n)
s.pad_left(width), s.pad_right(width)string::pad_left(s, width), string::pad_right(s, width); each takes an optional fill: string::pad_left(s, n, [fill])
no method formstring::join(parts, [sep]), string::from_code(n), string::is_valid_utf8(s), string::from_bytes(bytes)

Formatting: format specs​

A spec ends a template splice (${expr:spec}) or a {} placeholder of print or format; format_value(value, "spec") applies one directly. Errors and the : rules: Template strings & format specs.

[[fill]align][+| ][0][width][,|_][.precision][d|x|X|b|f|e|g]

PartMeaning
< > ^, with an optional fill before itAlign in the width. Strings default to the left, numbers to the right. ^ puts an odd fill character on the right.
+, a spaceA sign on non-negative numbers.
0Zero padding after the sign. Under a grouping the zeros group too.
, or _Groups a number's integer digits in thousands. _ groups x, X and b digits in fours.
.NFixed decimals, bare or with f. :f alone is 6.
d x X bInteger bases (ints only).
f e gFloat styles.

JSON and key order​

JSON encoding​

to_json(x) writes compact JSON, to_json(x, n) indents n spaces per level, from_json(text) reads it back. to_binary and from_binary round-trip the same values. Loading rules: JSON.

ValueJSON
a map with string keys, an array, a string, bool, nullan object, an array, a string, true/false, null
an int, a floatA number that reads back as the same kind. A float is written with every digit it needs to read back exactly.
a map whose keys are not strings{"$map": [[key, value], ...]}
a char{"$char": 65}
a float JSON cannot spell{"$float": "inf"}, "-inf" or "nan"
a class instance{"$type": "Hero", "$val": {fields}}
a shared_ptr handle, the first to its objectThe object, once: {"$id": 1, "$type": "Hero", "$val": {...}}
a shared_ptr handle, every later one{"$id": 1}
a weak_ptr handleThe same with $ref in place of $id. An expired one is null.

Map key order​

Keys follow one total order, the order a map iterates and serializes in. Lookup is hashed. More: Key types.

KeyIdentity and order
numbersBy value. 0.0 and -0.0 are one key. Every NaN is one key, ordered after the numbers.
different kindsNever one key: 1 and 1.0 are two, and a utf8_string is not the string of the same text.
a char and its one-character stringOne key, ordered as the string. The entry keeps the spelling that made it.
a char key in a map<string, V>Stored as its string.
a one-character string key in a map<char, V>Stored as its char. A longer string raises the char conversion's error.
an array, map or handleBy the identity of the object it holds, never its contents: two equal array literals are two keys.
a class value with operator< or operator<=>Ordered by it. Two keys are one when neither is less.
a class value with int hash() and neitherKeyed by hash() and operator== (identity without one), iterated by hash() value.
a class value with none of theseBy identity, with the warning map keys of class 'C' compare by identity: declare operator<=> (or operator<) or hash() to key its values by value
class keysIterate grouped by class name, ahead of handles.

Binary data​

A string holds any byte. s.to_bytes() and string::from_bytes(bytes) convert to and from an array<uint8>. Errors, limits and file reads: Binary data.

binary::reader​

s.reader() or binary::reader(s) reads the string from a cursor at 0, little-endian. Every read advances the cursor.

Reader callReads
int8() int16() int32() int64()A signed integer.
uint8() uint16() uint32()An unsigned integer. There is no uint64(): int64() reads the same eight bytes as a signed value.
float32(), float64()A float. float32 widens, float64 keeps every bit.
text(n)An n-byte text field, C's char[n]: the cursor moves exactly n. The text is the bytes before the first NUL (all n when there is none).
text()A C string: the bytes before the next NUL. The cursor moves past the NUL.
bytes(n)Exactly n raw bytes as an array<uint8>.
big_endian(), little_endian(), seek(pos), skip(n)Set the byte order or move the cursor. Each returns the reader, so calls chain.
pos(), size(), remaining(), at_end()Ask: the cursor, the byte count, the bytes left, whether the cursor is at the end.
unpack(layout), unpack(name, width, ...)A layout's fields in order, as a map<string, var>.
read(Class, layout)A default-constructed instance, its fields filled in declaration order, base fields first.
read: class against layoutThe field count and each field's kind (int, float, string for text, array for bytes) must match the widths.

binary::writer​

binary::writer w; mirrors the reader. Each call returns the writer.

Writer callWrites
int8(v) to int64(v), uint8(v) to uint32(v), float32(v), float64(v)The number. One that does not fit raises and writes nothing: Cannot write 256 as uint8 (0 to 255).
text(s)The text, then a NUL. A text that holds a NUL raises Cannot write text: the text holds a NUL at byte 3; raw data goes through bytes.
text(s, n)An n-byte field: the text, then NULs to n. A text of exactly n bytes fills the field with no terminator.
text(s, n), text longer than nRaises Cannot write text: the text is 9 bytes, longer than text(8).
bytes(b)Raw bytes: a string's, or an array of 0–255.
pack(layout, map)The map's values in the layout's order. A missing name or a value that does not fit raises before anything is written.
big_endian(), little_endian(), seek(pos)Set the byte order; go back to patch an earlier field.
pos(), size(), to_string()The cursor, the byte count, the bytes.

Layouts and widths​

NameRule
binary::layout(name, width, ...)A reusable layout, validated once (binary::layout fields total more than 9223372036854775807 bytes). Field order comes from the arguments, never from a map.
widthsbinary::int8, int16, int32, int64, uint8, uint16, uint32, float32, float64, binary::text(n), binary::bytes(n): values that describe an encoding, not types.
binary::bytes(n)Unpacks to an array<uint8> and packs exactly n bytes.
a width's methodssize name
a layout's methodssize count
load-time checksA wrong signature, an odd name/width pairing, a non-width where a width belongs, a read(Class, layout) whose class and layout do not match.

Regular expressions​

regex(pattern) and regex(pattern, flags) make a regex value. Matching is linear in the text: no pattern backtracks. Taught in Regular expressions; the constructs that are errors: no backtracking; bytes against characters: text kinds; load-time compilation: constant patterns.

Calls​

CallAnswers
r.search(text), r.search(text, start)The leftmost match at or after start, a regex::match, or null. The text before start still counts for ^ and \b.
r.matches(text)Whether the whole text matches, any way through the pattern: regex("a|ab").matches("ab") is true.
r.find_all(text)Every match, left to right, as an array of regex::match.
r.replace(text, with), r.replace_first(text, with)The text with every match (or the first) replaced by a replacement text, or by what a function returns for the regex::match.
r.split(text), r.split(text, max_splits)The pieces between matches. Each split's capture groups follow its piece. A count keeps the rest in the last piece.
r.pattern, r.flagsThe pattern and flags it was made with (read-only).
regex::escape(text)A pattern that matches the text literally.
m.text(), m[0]The whole match.
m[i], m["name"]A group by number or name; null for a group that took no part. A group in a loop keeps the text of the loop's last pass.
m.start(g), m.end(g)Its positions (group 0 when g is left out); -1 for a group that took no part.
m.size()The whole match plus every group.

Syntax​

ConstructMatches
a, \., \t \n \r \f \v \0The character. A backslash before punctuation or a space takes it literally; before a letter that names nothing it is an error.
\xNNA byte on a string; U+00NN on a utf8_string.
\uXXXX, \u{X}A code point (its UTF-8 bytes on a string).
.Any character but a newline (with flag s, any).
[abc], [a-z], [^...], [], [^]One character of the set, or not of it. - first or last is literal, [] matches nothing and [^] anything.
\d \w \s, \D \W \SAn ASCII digit, word character (letters, digits, _) or whitespace (space, tab, newline, carriage return, vertical tab, form feed), or anything else. Inside a class too.
^, $The start or end of the text (with flag m, of a line: \n ends one). $ does not match before a final newline.
\A, \zThe start or end of the text, whatever the flags.
\b, \BA word boundary, or a position that is not one.
(...), (?<name>...), (?:...)A capture group (numbered from 1 by its opening parenthesis), a named one (also numbered), a group that captures nothing.
x|yThe first alternative that leads to a match. An empty alternative matches empty.
* + ?, {n} {n,} {n,m}Repetition, as many as possible. A count runs to 1000. A brace that starts no count is a literal brace.
*? +? ??, {n,m}?Repetition, as few as possible.
(?i), (?-i), (?i:...)Turns flags on or off to the end of the enclosing group, or inside the group alone (any of i m s x).

Flags​

FlagEffect
iLetters match either case (ASCII letters).
m^ and $ match at line breaks.
s. takes a newline.
xSpaces and # comments outside a class are ignored.
another letter, or one twiceRaises.

Replacement text​

In a replacement textInserts
$1 to $99A group, taking the longest number the pattern has: $10 with one group is $1 then 0.
$0The whole match.
${n}, ${name}A group by number or name.
$$A dollar sign.
a group that took no partInserts nothing.
a group the pattern lacks, or a $ before anything elseRaises: regex: the replacement names group 2 at position 0, but the pattern has 1 group

Location builtins​

Path queries every engine carries, from Modules: where files are. Locations are absolute, with forward slashes and no trailing separator. Each requires the jai::filesystem privilege (Filesystem access is a host choice).

BuiltinAnswers
resolve_path(name)The file import name would load, asked from the calling file; "" when no rung has it.
current_script_dir(), current_script_path()The folder and file whose code is executing.
root_script_dir(), root_script_path()The folder and file the program started with, fixed for the run. A REPL or an inline program answers the working directory and "".
executable_dir() (alias bin_dir()), executable_path()The running executable's folder and file, fixed for the process.
app_data_dir(name)The platform's per-user folder for an app called name, for per-user saves: %LOCALAPPDATA%\name, ~/Library/Application Support/name, $XDG_DATA_HOME/name. A query only.
app_cache_dir(name)The per-user folder for a regenerable cache: below %LOCALAPPDATA%\name, ~/Library/Caches/name, $XDG_CACHE_HOME/name. A query only.
other platforms (Android)The host installs its own resolvers for both with engine::app_directory_resolvers.
working_dir()The working directory.
parent_dir(p)A normalized parent path, weakly canonicalized, so it can consult the filesystem.
file_name(p)The lexical last component of a path.
file_data(p)A map<string, var> about the file or folder the path ladder finds for p (keys below); null when nothing is there, so file_data(p)["modified"] polls without a try.

file_data keys​

KeyValue
pathCanonical, absolute.
filenameWith its extension.
extensionWith its dot, ".jai"; empty for a folder or a name without one.
createdInt milliseconds since the Unix epoch; null where the platform does not report it, as on Linux.
modifiedInt milliseconds since the Unix epoch.
sizeInt bytes, 0 for a folder.
is_directoryWhether it is a folder.

Reflection calls​

Every reflect:: call, from Reflection. A call that takes an instance v also takes a class name as a string.

Shape​

Taught in Ask: what shape is this?

CallAnswers
reflect::type_name(v)type_of, except that a typed container gives its canonical tag ("array<int>", not "array"). A reference answers what it refers to. A string is read as a value.
reflect::fields(v)One map per field: name, type, kind, access, static, from (the declaring class).
reflect::fields orderBase class fields first, then own, in declaration order on every engine and backend; a class's static fields follow its instance fields.
reflect::fields of a C++-bound classThe host's property schema; kind tells a plain field from a "signal" or "observable" member.
reflect::methods(v)One map per overload: name, arity, static, access, from, params (an array of {name, type, default} maps), sorted by name then arity. Property accessors and constructors are not listed.
reflect::has_field(v, "name"), reflect::has_method(v, "name")Bool; both walk the inheritance chain.
reflect::method_arguments(v, "name"), reflect::function_arguments("name")One params array per overload; empty for a host-registered function.

Read, write, call, construct​

Taught in Act: read, write, call, construct. get, set, invoke, bind and construct reach private members and private constructors.

CallIs
reflect::get(s, "hp")s.hp
reflect::set(s, "hp", 42)s.hp = 42; a typed field converts or raises the direct syntax's error.
reflect::invoke(s, "wound", 5)s.wound(5)
reflect::bind(s, "wound")The method as a callable that holds s and keeps it alive: the one spelling of a method taken as a value (Classes). A string, array or map is refused; wrap the call in a lambda.
reflect::call("ns::name", args...)A call of the global or namespace-qualified function.
reflect::construct("Class", args...)Class(args): a value; copies are independent.
reflect::construct_shared("Class", args...)new Class(args): a shared handle, as in spawned.push(reflect::construct_shared(row["type"], row["hp"])).
get, set, invoke given a class nameReach the class's static members.

Program-wide queries​

Taught in Navigate: the wider world.

CallAnswers
reflect::classes()Every class, script-declared and host-bound, sorted.
reflect::functions()Every function, namespace-qualified and sorted; no constructors.
reflect::globals()Global variable names, sorted.
reflect::bases(v)The base classes in declaration order, empty at a root.
reflect::is_a(v, "Class")v instanceof Class for a class named at run time: true when v holds an object of the class or of one derived from it; false for any other value, a string included. An unknown class name raises reflect::is_a: unknown class 'Nope'.
reflect::is_cpp_bound(v)For a class name, whether the host registered it; for a value, whether a C++ object backs it.
reflect::is_enabled(requirements...)Whether the host granted every named privilege ("filesystem", jai::filesystem, a custom permission name); false for an unknown name (Where files are).
reflect::instances("Class")The live instances of a class, in creation order.
reflect::generation("Class")A counter that moves whenever the class is redefined.

A non-class argument​

What each function does given a value that is neither an instance nor a string (5, an array, null), from Strings are class names. A string that names no class raises reflect::fields: unknown class 'hello', each function under its own name.

FunctionResult
fields, bases[]
has_field, has_method, is_cpp_boundfalse
methods, method_arguments, generation, instancesRaises reflect::methods expects a class or class name.
get, set, invokeRaises reflect::get expects an object or class name.

Web functions and the HTTP client​

The web:: encoders and the spider:: client, from Web. Failure texts: spider errors.

Encoding and query strings​

Taught in Percent-encoding and Query strings.

FunctionRules
web::url_encode(s)RFC 3986, for a path segment or any other URL part: A-Z a-z 0-9 - . _ ~ stay, every other byte is %XX in upper-case hex (PHP's rawurlencode).
web::form_encode(s)application/x-www-form-urlencoded, for a form body or query string: A-Z a-z 0-9 * - . _ stay, a space is +, every other byte is %XX (PHP's urlencode).
web::url_decode(s), web::form_decode(s)Each %XX back into its byte; form_decode also reads + as a space. A % without two hex digits after it is kept as written.
web::parse_query(s)A map<string, string>; keys and values are form-decoded.
web::parse_query edge casesA leading ? is skipped. A key without = has an empty value. An empty key is dropped. A repeated key keeps its last value.
web::parse_query_all(s)Keeps every value: a map<string, var> of array<string>, in arrival order.
web::build_query(m)Form-encodes a map, joined with & in the map's key order.
web::build_query valuesA string, number or bool is written as to_string writes it. An array repeats its key per element. A null value drops its key.
web::build_query errorsAny other value raises web::build_query: the value of 'm' is a map (or ... is not text, a number, a bool or an array of them).

Request options​

The options map of spider::catch, spider::get, spider::sling and spider::post (HTTP with spider::).

OptionMeaning
methodGET, HEAD, POST, PUT, PATCH, DELETE or OPTIONS, any case.
headersA map of names to text, number or bool values; overrides the defaults (User-Agent: jaiscript-spider/VERSION, Accept: */*, the content's type).
timeoutSeconds for the whole call, redirects included (default 30).
type"json", "text", "form" (a map sent as web::build_query spells it) or a media type such as "text/csv" for text content.
redirectsHow many to follow, 0 to 100 (default 5); 0 answers the redirect itself.

spider::Response members​

Taught in spider::Response.

MemberWhat it is
spider::Response(status, body)A new one; both optional: 200 and an empty body.
status, ok()The status code (int); true for 2xx.
body, json()The body's bytes; from_json of them.
urlThe URL that answered, after redirects; "" for a response a script built.
headersA writable map<string, string>. A received answer's names are lowercased and a repeated header is joined with ", ".
header(name)Reads any spelling of the name; "" when absent.
header(name, value)Sets a header, replacing any spelling of the name, and returns the response, so calls chain. Raises Response.header: 'N' is not a header name, or its value holds a line break or NUL.
cookiesThe Set-Cookie lines (array<string>).
set_cookie(name, value[, options])Adds a Set-Cookie line, the value percent-encoded. The name is a token.
clear_cookie(name[, options])Adds a Set-Cookie line that sets Max-Age=0.
set_cookie and clear_cookie optionsmax_age, expires (unix seconds), path ("/"), domain, secure (false), http_only (true), same_site ("Lax"; "" leaves it out).
cookie option textpath, domain and same_site hold no ; or control character (Response.set_cookie: option 'path' holds a ';' or a control character).

Random generator algorithm​

The formulas behind random, from Randomness: the algorithm, exactly. Every formula is part of the language, so a seed draws the same bits everywhere.

StepDefinition
generatorxoshiro256** 1.0 (Blackman and Vigna): four 64-bit words; a draw is rotl(s1 * 5, 7) * 9.
seedingThe words are four successive splitmix64 outputs from the seed: x += 0x9E3779B97F4A7C15, then z = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9, z = (z ^ (z >> 27)) * 0x94D049BB133111EB, z ^ (z >> 31).
next_int(lo, hi)Lemire's method over span = hi − lo + 1: the high word of draw × span, redrawn while the low word falls under (264 − span) mod span.
next_int over the whole int rangeOne raw draw.
next_float(lo, hi)fma(u, hi − lo, lo) with u = next_float(), one rounding; a result that rounds up to hi is the float just below it.
shuffleFisher–Yates from the last index down, element i swapped with the one at next_int(0, i).
pickThe element at next_int(0, size − 1).
parallel streamsElement i (the chunk, for parallel_reduce) of a loop that captures a generator draws from the stream splitmix64 seeds from mix(draw ^ mix(i + 0x9E3779B97F4A7C15)).
draw, mixdraw is the statement's one draw from the captured generator; mix is the seeding's output step.

ANSI escape sequences​

The terminal sequences a game prints, from Terminal Games: drawing a frame. ESC is the escape byte "\x1b".

SequenceEffect
ESC + "[?1049h", ESC + "[?1049l"Enter and leave the alternate screen: the shell's text comes back afterwards.
ESC + "[?25l", ESC + "[?25h"Hide and show the cursor.
ESC + "[2J"Clear the screen.
ESC + "[H"Move the cursor to the top-left corner.
ESC + "[K"Clear from the cursor to the end of the line, so a shorter line leaves nothing of a longer one.
ESC + "[38;2;R;G;Bm", ESC + "[48;2;R;G;Bm"24-bit text and background colour, where env_var("COLORTERM") ("" when unset) is "truecolor" or "24bit".
ESC + "[38;5;Nm"One of the 256 xterm colours.
ESC + "[0m"Back to the default colours.

Library at a glance​

jaiscript
math::vec3 p = math::vec3(1, 2, 3);
p.x = 10;                                     // a component is an lvalue
array<math::vec3> pts = [p, math::vec3(0, 0, 1)];
print(p * 2.0, " ", math::dot(p, p), " ", math::length(math::vec2(3, 4)), " ", pts[1]);

binary::writer w;
w.uint16(513); w.text("hi");
var r = w.to_string().reader();
print(r.uint16(), " ", r.text(), " ", r.at_end());

utf8_string u = "h\xC3\xA9llo";
print(u.size(), " ", u[1], " ", "h\xC3\xA9llo".size());

array<float> xs = [1.0, 2.0, 3.0];
parallel_for (auto& x : xs) { x *= 2.0; }
print(to_json(xs), " ", type_of(time::utc_now()));
print(to_json({"a": [1, 2]}, 2));
output
(20.0, 4.0, 6.0) 113.0 5.0 (0.0, 0.0, 1.0)
513 hi true
5 é 6
[2.0,4.0,6.0] time::date
{
  "a": [
    1,
    2
  ]
}
AreaSurfaceChapter
math functionsmath::floor ceil round trunc itrunc ifloor sqrt cbrt pow exp exp2 log log2 log10 abs sign fmod hypot saturate wrap remap sin cos tan asin acos atan atan2 sinh cosh tanh degrees radians radians_to_degrees degrees_to_radians is_nan is_inf wrap_add wrap_sub wrap_mul; constants math::PI math::EMath
vectors and colorsmath::vec2 vec3 vec4 ivec2 ivec3 color: value types with component fields (x y z w, r g b a; also width height depth) and component-wise operators. An ivec's zero divisor component raises Division by zero. A default math::color is opaque white; colors mix in OKLab. array<math::vec3> is a typed buffer.Math
vector functionsmath::dot cross length length_squared normalize distance distance_squared reflect project perpendicular angle_between rotate math::rotate_around math::angle math::from_angle (angles in radians); the component-wise math::lerp math::mix math::clamp math::min math::max family with unmix mix_rgb mix_hsv mix_in mix_out mix_in_out mix_out_in unmix_in unmix_out unmix_in_out unmix_out_inMath
vector methodslength length_squared normalized dot distance_to; on 2- and 3-component vectors cross rotated; on 2-component vectors rotated_around angleMath
host math typesJAI_BIND_VEC2 / VEC3 / VEC4 / IVEC2 / IVEC3 / COLOR in a C++ type's header make it cross the boundary as the native kind.Math Adapters
printing and conversionprint (tokens skip_newline skip_flush) format vformat format_value to_string type_of is_registered_type to_char utf8_string cast<T>; format specsContainers & Strings
textstring is bytes; utf8_string counts characters (size, u[i], substr, range-for). split() splits on whitespace (string::whitespace). String methods.Containers & Strings
containers and objectsarray and map methods, the array:: and map:: copies; merge pair (first second); same_object extend shared_from_this weak_from_thisContainers & Strings
regular expressionsregex(pattern, [flags]), regex::escape(text), regex::match: calls, syntax, flags i m s x, replacements $1 ${name} $0 $$. Linear time; bytes on a string, characters on a utf8_string; a constant pattern compiles at load.Containers & Strings
binary datas.reader() / binary::reader(s), binary::writer w;, binary::layout("field", width, ...) with r.unpack, w.pack and r.read(Class, layout): reader, writer, layouts. s.to_bytes() and string::from_bytes(b). array<uint8> / array<int8> are one-byte buffers.Containers & Strings
JSON and archivesto_json(x) compact, to_json(x, n) with n spaces per level; from_json(s) rebuilds class instances (through their constructor), chars and non-string map keys (encoding). to_binary from_binary to_base64 from_base64; base64_encode base64_decode for raw bytes.Containers & Strings
random numbersrandom r; (seeded by the system), random r(seed); (the same stream on every platform): next_int(lo, hi) inclusive, next_float() in [0, 1), next_float(lo, hi), next_bool(), pick, shuffle, next_bytes(n), seed(s). A copy replays its draws; state round-trips through every archive.Random Numbers & Crypto
cryptocrypto::random_bytes(n) random_hex(n) random_int(lo, hi): the system's secure generator, never seedable. sha256 sha512 sha1 md5 (hex, _bytes raw), sha256_file(path). hmac_sha256(key, message) hmac_sha512 (hmac_sha256_bytes hmac_sha512_bytes raw). equals(a, b) in constant time. password_hash(pw[, cost]) and password_verify(pw, hash): bcrypt as PHP writes it.Random Numbers & Crypto
web text (opt-in: register_web)web::html_escape(s) (& < > " '), web::html_unescape(s) (HTML5 references, as a browser reads them), web::url_encode / url_decode (RFC 3986), web::form_encode / form_decode (space as +), web::parse_query, web::parse_query_all, web::build_query (key order), web::parse_url to a web::url whose to_string() joins it back.The web:: Library
templatestemplate scoped_template scoped_template_text raw, each answering a web::html (to_string)The web:: Library
HTTP client (opt-in: register_spider, a host transport, the network permission)spider::catch(url[, options]) (also spider::get), spider::sling(content, url[, options]) (also spider::post(url, content[, options])). Options method, headers, timeout, type, redirects. Each answers a spider::Response (status, headers, cookies, body, url, ok(), json(), header(name), set_cookie, clear_cookie).HTTP with spider::
atomics (opt-in: register_atomics)atomic<int> atomic<float> atomic<bool>: a host's std::atomic bound by reference into every engine that shares it; never copied. load store exchange compare_exchange(expected&, desired), fetch_add fetch_sub (int, float), fetch_and fetch_or fetch_xor (int). += -= and ++ -- (int) are single atomic steps; a typed slot is a load.Dynamic Binder
timetime::now() engine_elapsed() execute_elapsed() unix_time() unix_ms() date_now(template) utc_now() local_now() date_from_unix(seconds) utc_date(y, m, d, ...) local_date(y, m, d, ...), the value types time::stopwatch and time::dateTime
time::stopwatchstart stop delta elapsed pause resume is_running is_pausedTime
time::datefields year month day hour minute second millisecond weekday yearday utc; methods unix unix_ms format to_string to_utc to_local add_days add_months add_years add_hours add_minutes add_seconds betweenTime
waitingsleep(seconds), a builtin of every engine: suspends a run the host started with engine::start until the time has passed, and blocks anywhere else.Coroutines
coroutine handlesnext advance result doneCoroutines
parallelismparallel_for (auto& x : arr) { ... } , parallel_for (int i = a; i < b; i++) { ... } , parallel_transform(arr, f) and parallel_reduce(arr, init, step, combine): deterministic at any worker count; thread_count. A body that writes enclosing state raises parallel_for: body writes enclosing state 'total' at 11:31.Parallel Loops
reflectionreflect::: type queries, fields and methods by name, reflect::bind(obj, "name"). type_name is_cpp_bound has_field has_method classes bases generation fields instances get set invoke bind call construct construct_shared methods method_arguments functions globals function_arguments is_enabled template_output_limit scoped_template_output_limit scoped_template_dirsReflection
files and modulesinclude import (jai::force) import_recheck_interval, under the jai::filesystem privilege; the location builtins root_script_path root_script_dir current_script_path current_script_dir executable_path executable_dir bin_dir working_dir parent_dir file_name resolve_path app_data_dir app_cache_dir file_dataModules
signals (when the host binds the signal type)Signal: connect disconnect connected; SignalEmitter: those and emitAPI signatures
standalone runnerARGS read_file write_file file_exists delete_file move_file dir_exists make_dirs writable_dir list_dir zip_entries zip_extract env_var key_down read_key term_cols term_rows load_sound play_sound stop_sounds net_host_name net_local_addresses Download NetChannel NetServerRunner host API

What a bare engine has. jai::engine::make() alone runs the whole language with these builtins:

  • a print that concatenates its arguments, and template strings with format specs (format_value)
  • the builtin container and string methods and their array:: forms
  • math:: (functions, vectors, colors, wrap_*), regex, and binary:: readers and writers with string::from_bytes
  • same_object, extend, thread_count, parallel_transform and parallel_reduce, sleep
  • the location builtins (executable_dir, file_data, resolve_path and the rest)

jai::stdlib::register_all adds the formatted print, format, to_string, type_of, JSON and binary serialization, the string:: functions, to_char, random, time::, crypto:: and reflect::. web:: and spider:: are separate opt-ins.