Memory Model
What the collector does, which values are references, and which are copied.
PickleScript has a tracing garbage collector. You do not free ordinary values,
and you do not copy them by hand: there is no clone() to reach for, and no
cell().
The thing worth knowing is which values share storage. Two of the three answers are "the same object", and guessing wrong is the usual source of "why did my function change my argument" bugs.
Lists, maps, classes and structs are references
class Box {
var n: int
constructor(n: int) {
this.n = n
}
fn bump() {
this.n = this.n + 1
}
}
fn main() {
var xs = [1, 2, 3]
let alias = xs
alias[0] = 99
println(xs[0]) // 99 - one list, two names
let a = Box(1)
let b = a
b.bump()
println(a.n) // 2 - one object, two names
}
Binding a list, map, class or struct to a second name does not copy it. To get an independent value, build a new one explicitly.
Everything else is copied
Primitives (int, float, bool, char, byte) and string are values.
A string is an immutable byte sequence, so a second name can never mutate the
first:
fn main() {
var s = "hi"
var t = s
t = "bye"
println(s) // hi - s was never touched
}
Enums are values too. == on a class or a struct compares identity, so two
structs with identical fields are not equal unless they are the same
object. See Structs.
Printing collections
println does not render a list or a map as text. It prints the type and the
length, which is enough to confirm shape while debugging:
fn main() {
println([1, 2, 3]) // List(len=3)
println({"a": 1, "b": 2}) // Map(len=2)
println(len([1, 2, 3])) // 3
}
Indexing a map with a key that is not present yields the zero value of the
map's value type, 0, 0.0 or "". That makes m["missing"] useless as an
absence test; use m.has("missing") or an optional-returning lookup.
When you do need to manage memory
Raw pointers, & and *, and the raw-buffer builtins live behind an
unsafe block. See Manual memory.
