get()
Read an array position
Use a zero-based index to read an item at a known position.
scores = [8, 12]
print(get(scores, 1))
12
Index 1 selects the second item.
Read a dictionary key
Supply the field name rather than its position.
player = {name = 'Ada'}
print(get(player, 'name'))
Ada
The lookup matches the name key.
Provide a fallback for a missing key
Give get() a third argument when a missing key needs a default.
settings = {theme = null}
print(get(settings, 'volume', 70))
print(get(settings, 'theme', 'dark') == null)
70
true
The fallback applies to an absent key. The stored null is returned as it is.
Read a character from text
For text, an index selects one Unicode scalar.
print(get('éclair', 0))
é
The first character occupies more than one UTF-8 byte. It still takes a single text index.
Read a packed field
Get a view of the first record, then read its x field.
points = create({x = f32}, 2)
points[0].x = 4
first = get(points, 0)
print(get(first, 'x'))
4
The record returned by get() shares the packed array's storage.
Use 'get' to read from a collection or packed value. Supply a fallback when an absent key should have a useful default.
Arrays and dictionaries
Use a zero-based index for an array and a key for a dictionary. A missing key uses the third argument when supplied. An explicitly stored null is still a value.
print(get({name = 'Ada'}, 'name'))
print(get([8], 4, 0))
Output
Ada
0
Text and packed data
A text index selects a character and a range selects a slice. An indexed packed record or slice can be a view into existing storage. Use copy to make independent storage.
A native library key retrieves a bound function or an exported member. See set to write a value instead.
Reads an element or field using indexed access.
Signature
get(value, key[, fallback])
Parameters
A table-backed value and key, packed value and index/field, text and signed scalar index or range, or a native library and bound/exported member name. The fallback form requires array, dict, table or module.
Returns
The selected value, a slice, or the fallback for an absent key. A stored null is returned as null.
Behavior
Leaves the source unchanged. Indexing a dictionary function leaves it unbound. Packed record and slice access can return a live view.
Errors
Bad receiver or index, bounds violations without a table fallback, invalid packed view, or closed library or unresolved library member.
Example
assert(get({price = null}, 'price', 5) == null)
assert(get([1], 9, 0) == 0)