types.Table.swap
Method on every
tableExchanges 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
key1 | any | first key |
key2 | any | second 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
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 objectSee also
rawset | Sets the slot at key to value, creating the slot if it does not exist yet. |
rawget | Returns the value stored under key, without going through a metamethod. |
replace_with | Replaces the table's entire contents with a copy of other's slots, in place. |
| table | class index |