Quirrel4.41.0

types.Array.totable

Method on every array
pure array.totable(): any

Builds a table from the array's elements.

Return value

A new table.

Whether the array holds [key, value] pairs or plain values decides how: if the first element is a 2-element array, every element must be one, and each becomes a key, value slot in the result. Otherwise every element must be a string, number, bool or null, and each becomes both the key and the value of its own slot, as if building a set.

Errors

Throws totable() expected array of pairs [[key, value], ...], size of the each pair array must be exactly 2 elements when the first element is a pair but a later one is an array of some other size.

Throws totable() expected array of pairs [[key, value], ...] or array of simple types ["key1", "key2", ...] when the two forms above are mixed, or an element is neither.

Example

examples/types/array/totable.nut
let t1 = [["a", 1], ["b", 2]].totable();   // array of [key, value] pairs
println("t1.a =", t1.a, "t1.b =", t1.b);

let t2 = ["x", "y"].totable();               // array of simple values: value becomes the key too
println("t2.x =", t2.x, "t2.y =", t2.y);

try { [["a", 1], ["b", 2, 3]].totable() } catch (e) { println("pair with 3 elements throws:", e); }
try { [1, [2]].totable() } catch (e) { println("non-pair element throws:", e); }
Output:
t1.a = 1 t1.b = 2
t2.x = x t2.y = y
pair with 3 elements throws: totable() expected array of pairs [[key, value], ...], size of the each pair array must be exactly 2 elements
non-pair element throws: totable() expected array of pairs [[key, value], ...] or array of simple types ["key1", "key2", ...]

See also

tostringReturns the default text representation of this array.
keysReturns an array of every key in the table.
arrayclass index