Create, append, read and replace
This complete indicator uses fixed numbers so the output is easy to inspect. On each execution it creates an empty float array, appends 10 and 20, then replaces the first element with 15. The resulting collection is [15, 20], its size is 2, and its average is 17.5. Runtime assertions describe the expected result; run the script on a chart to execute them.
| Operation | Effect | Required condition |
|---|---|---|
| array.new<float>(0) | Creates an empty float array | No readable element yet |
| array.new<float>(3, 0.0) | Creates three zero-valued elements | Size is 3, not reserved capacity |
| array.from(10.0, 20.0) | Creates two elements from values | Elements have a compatible common type |
| array.push(a, value) | Adds a new last element | Keep growth within your chosen limit |
| array.get(a, i) | Reads an existing element | Index must address an element |
| array.set(a, i, value) | Replaces an existing element | Does not create a missing position |
//@version=6
indicator("Array operations and checks")
array<float> values = array.new<float>(0)
array.push(values, 10.0)
array.push(values, 20.0)
array.set(values, 0, 15.0)
float first = array.get(values, 0)
float last = array.get(values, array.size(values) - 1)
float mean = array.avg(values)
if array.size(values) != 2 or first != 15.0 or last != 20.0 or mean != 17.5
runtime.error("Expected [15, 20] with average 17.5")
plot(mean, "Expected 17.5")