Values
Values include literals, strings, collections, functions, and native handles. Module documentation defines the helpers for each value type.
Contents
Literal classes
| Class | Examples |
| Nil and booleans | nil, true, false |
| Integers | 123, 0xff, 0o77, 0b1010, sized integer literals |
| Floats | 3.14, sized float literals |
| Strings | "text", 'text', triple-quoted strings, formatted strings |
| Lists | [1, 2, 3] |
| Dicts | {"name": "ny"} |
| Sets | Set values from standard-library helpers. |
| Tuples | (1, 2, 3) and (). |
| Ranges | Range values used by iteration and case. |
| Functions | Named functions and fn(...) { ... } values. |
| Native values | Pointers, handles, layouts, extern values. |
use core
def count = 123
def message = f"value={count}"
def items = [count, 2]
mut lookup = dict()
Rules
- Runtime representation is not a source-level type contract. Use predicates and conversions instead of inspecting tags, pointer shapes, or box bits.
niland integer0are distinct even though both are falsy.- Rebind list updates such as
appendandextend; they may return a new list handle. A bare{}is immutable; usedict()for a mutable accumulator. - Strings store bytes, while generic string slicing uses UTF-8 code-point indices. Check the specific API before crossing a byte or native boundary.
Typed and dynamic representation
The language distinguishes semantic values from their runtime transport representation. Typed arithmetic, function parameters, layout fields, and native ABI integer slots use raw signed 64-bit int values. Dynamic values such as any and heterogeneous containers may box values so the runtime can distinguish integers, heap objects, and native pointers.
Programs must not depend on a tag bit, pointer shape, or other box encoding. Use type predicates and conversion APIs instead. bigint is the explicit arbitrary-precision type for values outside the signed 64-bit range. See Numbers for the numeric tower and conversion rules.
Dynamic values ride on an ABI-level helper layer; its names stay visible for diagnostics. __flt_* functions carry boxed float arithmetic, comparisons, NaN/inf predicates, hashing, and the libm transcendentals. __bigint_* functions carry exact arithmetic, number-theory helpers, and conversions behind bigint once values promote past the 64-bit range; the user surface is bigint(value) and the core.math.big APIs. __cstr_cmp, __cstr_concat, and __cstr_eq compare and join raw C strings, __i64_to_cstr_raw and __f64_to_cstr_raw render raw fixed text, and __cstr_to_str copies into a managed string. The same pattern holds for the container, OS, and GC families: __str_*, __list_*, __dict_*, __gc_*, and friends are the raw substrates behind the matching core/ APIs; __is_nil and __is_int are the library-facing spellings that core/mod.ny and dynamic-value fixtures call, while programs keep the is_nil/is_int predicates. The C-string helpers take raw FFI-pointer cstr values, not managed strs. Application code keeps using the operators, predicates, and conversion APIs; these helpers exist for the runtime, FFI boundaries, and ABI debugging. The fixtures etc/labs/tests/lang/values/dynamic-float-arithmetic-abi.nshape, etc/labs/tests/lang/values/bigint.nshape, etc/labs/tests/lang/values/bigint-pidigits.nshape, and etc/labs/tests/lang/values/intrinsic-conversion-render.nshape pin the visible behaviors on both execution routes.
Nil
nil and integer 0 are distinct values, although both are falsy. Their type identity is preserved through compile-time evaluation, any values, function values, and dictionaries. APIs that use absence, such as filter_map, must return nil rather than integer 0.
use core
assert(nil != 0, "nil identity")
assert(!nil && !0, "falsy values")
assert(to_str(nil) == "nil", "nil string")
Dynamic transport must preserve that identity, and compile-time evaluation keeps it too: nil literals parse with token NY_T_NIL, and the proof evaluator in the lowerer refuses to prove a nil literal as an i64 constant, so integer fast paths cannot silently fold nil into a proven 0. Producers that need nil as a value re-derive it from the token kind rather than the integer payload.
The dynamic-transport contract example below passes on the current build and is the gate fixture etc/labs/tests/lang/values/nil-dynamic-identity.nshape; it stays a regression check for any transport that changes the word conventions of dynamic values.
use core
def any boxed = nil
assert(is_nil(boxed) && type(boxed) == "nil", "any identity")
mut d = {"_": 0}
d = d.delete("_")
d = d.set(nil, "missing")
d = d.set(0, "zero")
assert(d.get(nil) == "missing" && d.get(0) == "zero", "dictionary keys")
Strings
Strings are byte-length values. Generic string slicing uses UTF-8 code-point indices. APIs that cross native, file, socket, or binary-parser boundaries document whether they expect text or raw bytes.
Formatted strings use expression interpolation:
f"name={name} count={n}"
A trailing top-level = keeps the expression text as a label:
f"{name=}"
f"{count + 1=}"
Lists
Lists are ordered sequences. list(n) creates an empty list with reserved capacity n; it does not create n initialized elements. The initial length is zero.
use core
def reserved = list(4)
assert(reserved.len == 0, "capacity is not length")
mut xs = list(4)
xs = xs.append(4)
xs = add(xs, 5)
assert_eq(xs, [4, 5], "retain list updates")
append, add, and extend return the updated list value. Retain the return value: an update may produce a replacement list, so a call whose result is ignored need not update the binding.
Do not rely on whether another alias sees an update. Use the returned value when continuing with the updated sequence; use clone when an API needs a detached mutable copy.
Indexing a reserved-but-empty slot is not valid. Use append, a literal, or a standard-library helper that fills the list before reading by index.
Indexing
Lists, tuples, strings, bytes, and ranges support integer indexing:
use core
def xs = [1, 2, 3]
def tp = (4, 5, 6)
def text = "abcd"
def rg = range(2, 8, 2)
assert(xs[0] == 1 && xs[-1] == 3, "list indexes")
assert(tp[1] == 5, "tuple index")
assert(text[2] == "c", "string index")
assert(rg[-1] == 6, "range index")
Negative indices count from the end. Out-of-range or non-integer indices panic; try/catch can catch that panic. Dict indexing returns the stored value or the runtime default for a missing key. get(key, fallback) names the fallback.
Dicts
Dicts map keys to values. value.get(key, fallback) returns fallback when the key is absent.
use core
def empty = {}
def cfg = {"port": 8080}
def port = cfg.get("port", 80)
def host = cfg.get("host", "127.0.0.1")
{} is the empty dict literal in expression context. Non-empty dict literals use key/value pairs, for example {"key": value}.
Frozen and mutable literals
A bare {} is immutable and set silently leaves it unchanged. Use dict() for a mutable accumulator, seed a literal with a value, or clone an existing literal:
use core
mut out = dict()
out.set("ok", true)
Pre-populated literals such as {"ok": true} are mutable.
Lookup, insertion, and identity
Dict keys are compared by value identity: nil, 0, and "0" are three distinct keys. get(key, fallback) returns the fallback for a missing key; indexing a missing key returns the runtime default value.
A dict grows its table when the load threshold is reached; a growing dict allocates a new table and reinserts existing entries. A reference to the dict value stays valid across growth - the dict is a single managed object, not a pointer to its table. Iteration order over keys, values, and items is not a stable program contract across insertions and resizes.
List updates
List updates can be chained by retaining each returned value:
use core
mut xs = []
xs = xs.append(1)
xs = xs.append(2)
assert_eq(xs, [1, 2], "retained updates")
Core idioms
| Form | Meaning |
; | Comment marker, not a statement terminator. Newlines separate statements. |
cond ? a : b | Ternary selection. |
value ?? fallback | Nil coalescing - selects fallback when left side is nil. |
value?.member | Optional chaining - returns nil when receiver is nil. |
dict.get(key, default) | Safe lookup with fallback for missing keys. |
dict.set(key, value) | Mutates in place. Retaining the setter's return re-reads the mutated object, so chained setter calls stay in sync. |
list.append(item) | Returns the updated list; retain the result because growth may replace the value. |
list.extend(other) | Returns the updated list; retain the result because growth may replace the value. |
clone(value) | Detached mutable copy of a dict or list. |
is_dict(v), is_list(v), is_int(v) | Runtime type predicates. |
Receiver methods
Receiver methods wrap module helpers. The module API owns receiver availability; values do not gain receiver methods on their own.
When exact behavior matters, check the module page:
ny doc get core.str
ny doc search --symbols append
Check the owning module for the exact receiver methods and aliases. The available surface depends on module exports; a method name is not guaranteed for every value type.
Sequence operations
Strings and lists can be repeated with *:
"ha" * 3
[1, 2] * 2
Standard sequence helpers include sort, sorted, swapped, slice, keys, values, and items. The exact exported names and receiver aliases belong to core, core.str, and core.iter.
sort(xs) sorts xs in place and returns the same sorted list. sorted(xs) returns a sorted copy and leaves xs unchanged.
Equality and representation
Value kind controls equality. Scalars compare by value: integers, floats, booleans, strings, nil, and ranges. Lists, tuples, and dicts compare by element/value equality. nil is not equal to 0 and is not equal to the empty string. Type predicates such as is_str, is_int, is_dict, and is_nil report the runtime kind; use them instead of inspecting a tag or pointer.
Debug text, display text, and serialization have separate APIs. Use encoder/parser APIs when you need a stable external representation. to_str produces a display string; repr produces a debuggable spelling; parsers and encoders such as json_encode/json_decode own the stable wire form.
Related
- Types for static type expressions.
- Tooling for parser and encoder modules.
- Numbers for the numeric tower and conversions.
- Troubleshooting for string/byte and list-capacity pitfalls.