deep.copy_graph
Defined in module
"deep"from "deep" import copy_graphcopy_graph(value): any
Copies the object graph: shared parts stay shared, and an instance is copied by its _deepclone()
Parameters
value | any | the value to copy |
Return value
The copy.
Errors
Throws copy_graph: the value is nested deeper than 1000 levels for tables and arrays nested deeper than that between two _deepclone calls, and Native stack overflow at about 50 nested _deepclone methods that call cloner. An error in a _deepclone method goes to the caller, also from throw null.
Notes
- Each table, array and copied instance is copied one time, so a subtree that two places share stays shared in the copy, and a cycle is copied as a cycle; table keys are not copied.
- An instance whose class has a
_deepclone(cloner)method is copied by that method.clonercopies a value with the same rules and the same record of copies, so the method can copy its fields with it. An instance without_deepclonestays shared, and so do classes and functions. - A weakref stays a weakref, and the copies are not frozen.
A cycle through an instance with _deepclone is not supported, because the method runs again for the same instance before it returns.
Example
from "deep" import copy_graph
let shared = [1, 2]
let src = { a = shared, b = shared }
let graph = copy_graph(src)
println(graph.a != shared, graph.a == graph.b)
class Inventory {
items = null
owner = null
constructor(items, owner) {
this.items = items
this.owner = owner
}
function _deepclone(cloner) {
let res = clone this
res.items = cloner(this.items)
return res
}
}
let inv = Inventory(["sword"], "player")
let inv2 = copy_graph(inv)
inv2.items.append("shield")
println(inv.items.len(), inv2.items.len(), inv2.owner)Output:
true true
1 2 playerSee also
copy | Copies tables and arrays deeply, as deep_clone() of underscore.nut does |
| deep | module index |