Quirrel4.53.0

deep.copy

Defined in module "deep"
from "deep" import copy
copy(value): any

Copies tables and arrays deeply, as deep_clone() of underscore.nut does

Parameters

valueanythe value to copy

Return value

The copy; an instance comes back as it is.

Errors

A class and a table with a map slot go through map(), as in the script, so a class with no map member throws the index 'map' (type='string') does not exist. As in the script, from the top level of a script 49 nested tables or arrays copy, a 50th only when it is empty, and deeper ones throw Native stack overflow; so do about 50 nested map slots that call the copy function, which the script can copy.

Notes

Each table and array is copied where it is found. A subtree that two places share becomes two copies, and a cycle stops at the depth limit. The copies are not frozen. A weakref read from a container is read as its target, as foreach does, and the target is copied.

Example

examples/deep/copy.nut
from "deep" import copy

let shared = [1, 2]
let src = { a = shared, b = shared }

let plain = copy(src)
println(plain.a != shared, plain.a == plain.b)

class Inventory {
  items = null
}
let inv = Inventory()
println(copy(inv) == inv)
Output:
true false
true

See also

copy_graphCopies the object graph: shared parts stay shared, and an instance is copied by its _deepclone()
is_relaxed_equalCompares two values deeply: equal tables and arrays, and instances by their isEqual() method
is_strict_equalCompares as is_relaxed_equal() does, but numbers are equal only with the same type and the same bits
deepmodule index