Quirrel4.41.0

types.Array.clone

Method on every array
clone(): any

Makes a shallow copy of the array.

examples/types/array/clone-basic.nut
let squad = ["healer", "tank"];
let backup = clone squad;
backup.append("mage");
println("squad =", ", ".join(squad));
println("backup =", ", ".join(backup));
Output:
squad = healer, tank
backup = healer, tank, mage

Return value

A new array with the same elements.

Notes

clone is a language keyword (the clone operator), so a.clone() and a.$clone() do not compile: the parser expects an identifier after . and rejects the keyword. Write clone a instead, or, if the call has to be built from a string, a["clone"](). With #forbid-clone-operator the word is an ordinary identifier and a.$clone() compiles.

The copy is shallow: an element that is itself a table, array, class or instance is not copied, so the original and the clone reach the same nested object, and a change through one is visible through the other. Only the top-level list of elements is independent.

A frozen array clones into a plain, unfrozen one; freezing is not part of what gets copied, see is_frozen.

Example

examples/types/array/clone.nut
// clone is a language keyword, so a.clone() does not even parse
try { compilestring("return [].clone()") } catch (e) { println("[].clone() throws:", e); }

let a = [1, [2, 3]];
let b = clone a;      // use the operator instead
b[0] = 99;
b[1].append(4);          // the nested array is shared: this is a shallow copy
println("a[0] =", a[0], "b[0] =", b[0]);
println("a[1].len() =", a[1].len());     // grew through b, because a[1] and b[1] are the same array
Output:
[].clone() throws: ERROR: expected 'IDENTIFIER'
a[0] = 1 b[0] = 99
a[1].len() = 3

See also

replace_withOverwrites this array's elements with other's.
freezeReturns a reference to obj with the immutable flag set.
is_frozenReports whether this array reference is frozen.
arrayclass index