Quirrel4.41.0

types.Table.swap

Method on every table
table.swap(key1, key2): any

Exchanges the values stored at key1 and key2.

The binding carries no declaration string, so the VM cannot report parameter names. The names above are from this page; the types and attributes still come from the VM. The VM also cannot tell an optional parameter from a variadic tail here, so read the brackets and any trailing ... from the prose below, not from the signature.

Parameters

key1anyfirst key
key2anysecond key

Return value

The table itself.

Errors

Throws the index doesn't exist if either key is not present. Throws Cannot modify immutable object when the table was frozen with freeze().

Notes

Takes exactly two arguments. Both keys must already exist - swap never creates a slot, unlike rawset.

The same method also backs array and instance; on an array the two arguments are treated as indices instead of keys, and negative indices count from the end.

Example

examples/types/table/swap.nut
let t = {a=1, b=2}
let r = t.swap("a", "b")
println("r == t:", r == t)
println("t.a =", t.a, "t.b =", t.b)

try {
  t.swap("a", "missing")
} catch (e) {
  println("t.swap(\"a\", \"missing\") throws:", e)
}

let frozen = freeze({a=1, b=2})
try {
  frozen.swap("a", "b")
} catch (e) {
  println("frozen.swap(\"a\", \"b\") throws:", e)
}
Output:
r == t: true
t.a = 2 t.b = 1
t.swap("a", "missing") throws: the index doesn't exist
frozen.swap("a", "b") throws: Cannot modify immutable object

See also

rawsetSets the slot at key to value, creating the slot if it does not exist yet.
rawgetReturns the value stored under key, without going through a metamethod.
replace_withReplaces the table's entire contents with a copy of other's slots, in place.
tableclass index