Arrays
ton.array nums = [1, 2, 3]
push(nums, 4) // [1, 2, 3, 4]
print(nums[0]) // 1
nums[0] = 10 // [10, 2, 3, 4]
print(len(nums)) // 4
See Built-in native functions for the full set of array operations (push/pop/shift/unshift/slice/join/sort/reverse/contains/indexOf/map/filter/reduce/find/any/all). Indexing out of bounds is a runtime error, not nil.
Strings also support read-only indexing — s[0] is the first character, as a 1-character string. Strings are immutable: s[0] = "x" is a runtime error; build a new string with replace()/substring()/the ton.strings module instead.
Spread (...) splices another array's elements into a literal in place:
ton.array a = [1, 2, 3]
ton.array b = [0, ...a, 4] // [0, 1, 2, 3, 4]
ton.array both = [...a, ...a] // [1, 2, 3, 1, 2, 3]
The spread expression must itself be an array — spreading anything else is a runtime error.
Negative indices and slices (since beta-2.0.0) — a[-1] is the last element. a[start:end] returns a new array from start up to (not including) end; either bound can be left out, and both can be negative. Slices work on strings too.
ton.array a = [10, 20, 30, 40, 50]
print(a[-1], a[1:3], a[:2], a[3:], a[-2:]) // 50 [20, 30] [10, 20] [40, 50] [40, 50]
print("TON618"[0:3], "TON618"[-3:]) // TON 618
Destructuring — unpack an array into variables, with ...rest collecting what's left:
ton.let [first, second, ...others] = a
print(first, second, others) // 10 20 [30, 40, 50]
Method syntax — every array function can be called on the array itself (see Method syntax):
ton.array scores = [12, 7, 30, 18]
print(scores.filter(s => s > 10).map(s => s * 2).sorted()) // [24, 36, 60]
print(scores.sum(), scores.max(), scores.len(), scores.length)