Quirrel4.53.0

deep.copy_graph

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

Copies the object graph: shared parts stay shared, and an instance is copied by its _deepclone()

Parameters

valueanythe 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

A cycle through an instance with _deepclone is not supported, because the method runs again for the same instance before it returns.

Example

examples/deep/copy_graph.nut
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 player

See also

copyCopies tables and arrays deeply, as deep_clone() of underscore.nut does
deepmodule index