add()
Append to an array
Pass the target array and a value to put at the end.
scores = [8]
add(scores, 12)
print(scores[1])
12
The new value is the second item.
Insert at a position
Pass an array index as the second argument and the new value as the third.
scores = [8, 15]
add(scores, 1, 12)
print(scores[1], scores[2])
12 15
The old item at index 1 moves one position to the right.
Store a dictionary entry
The three-argument form accepts a dictionary key.
player = {name = 'Ada'}
add(player, 'score', 10)
print(player.score)
10
The new key and value are stored in player.
Join two pieces of text
For two text values, add() returns a new string.
print(add('Hello, ', 'Ada'))
Hello, Ada
The result is the combined text. The input values are unchanged.
Use 'add' to build a collection one item at a time. The two-argument collection form appends. The three-argument form accepts a position or key.
Arrays and dictionaries
An array insertion shifts the later items. Use an index equal to the length to insert at the end. To store a value in a dictionary, supply the key explicitly.
scores = [8, 12]
add(scores, 1, 10)
print(scores[1])
Output
10
Text and packed data
With two text values, 'add' returns a new string. A growable packed array can accept a compatible item. Fixed-size or pinned storage can reject growth.
See set to replace an existing array item and remove to delete one.
Appends, inserts, stores or concatenates.
Signature
add(target, value) or add(target, key, value)
Parameters
Two arguments accept text plus text, or an array, hybrid or growable packed array plus a value. Three arguments accept a mutable collection, key and value. An array insertion index is signed and can equal its length.
Returns
The mutated collection or the new concatenated string.
Behavior
Array insertion shifts later elements. Other three-argument forms use indexed assignment. Two-argument text addition is immutable.
Errors
Invalid receiver or operands, out-of-range insertion, packed conversion failure or inability to grow pinned or fixed storage.
Example
a = [1, 3]
add(a, 1, 2)
add(a, 4)
assert(a[1] == 2 and add('a', 'b') == 'ab')