Quirrel4.41.0

types.Instance.clone

Method on every instance
clone(): any

Creates a new instance of the same class, copying this instance's own field values into it.

examples/types/instance/clone-basic.nut
#forbid-clone-operator
class Loadout { ammo = 10 }
let a = Loadout()
let b = a.clone()
println("a.ammo =", a.ammo, "b.ammo =", b.ammo, "a != b =", a != b)
Output:
a.ammo = 10 b.ammo = 10 a != b = true

Return value

A new instance. Its fields hold shallow copies of this instance's field values: a field holding an array or table is shared, not deep-cloned, with the original.

Notes

Does not run constructor. If the class defines a _cloned metamethod, it runs once afterward as newInstance._cloned(oldInstance). The new instance is this, the original is the only explicit argument. Use _cloned to deep-copy a field that must not be shared, or to fix anything a plain field-by-field copy gets wrong.

clone is a compiler keyword by default (the clone x operator), so someInstance.clone() does not even parse unless the file starts with the #forbid-clone-operator directive.

Example

examples/types/instance/clone.nut
#forbid-clone-operator
class Foo {
  x = 1
  // this is the new instance; the one explicit argument is the original
  function _cloned(old) { this.x = old.x * 10 }
}
let a = Foo()
let b = a.clone()
println("a.x =", a.x, "b.x =", b.x, "a != b =", a != b)
Output:
a.x = 1 b.x = 10 a != b = true

See also

getclassReturns the class this instance was constructed from.
cloneAlways fails. clone is one of the type-methods every built-in delegate carries, but the VM's generic clone operation explicitly refuses a class.
instanceCreates a new instance of the class without running its constructor.
instanceclass index