types.Instance.clone
Method on every
instanceclone(): any
Creates a new instance of the same class, copying this instance's own field values into it.
#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 = trueReturn 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
#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 = trueSee also
getclass | Returns the class this instance was constructed from. |
clone | Always fails. clone is one of the type-methods every built-in delegate carries, but the VM's generic clone operation explicitly refuses a class. |
instance | Creates a new instance of the class without running its constructor. |
| instance | class index |