Skip to content

Arrays

An array stores an ordered sequence whose elements all have the same type. In Pop source, {T} and Array<T> are two spellings for the same array type:

local names: {String} = { "Ada", "Grace", "Linus" }
local scores: Array<Int> = { 10, 20, 30 }

An array literal needs an expected type. The annotation tells Pop which element type to use and also gives an empty literal enough context:

local empty: {String} = {}

Writing only local values = {1, 2, 3} is rejected in 0.1.0-rc.6 because an untyped array literal does not select its own array type.

Pop arrays use one-based positions: the first element is at index 1.

local names: {String} = { "Ada", "Grace" }
local count = Array.length(names) -- 2
local first = names[1] -- String?

Ordinary indexing returns an optional value. An index smaller than 1 or greater than the length produces nil instead of reading invalid memory.

When the program has already established that a position is valid, Array.get returns the element directly and traps on an invalid index:

if Array.length(names) > 0 then
local first = Array.get(names, 1)
print(first)
end

Choose ordinary indexing when absence is part of the operation, and checked Array.get when an invalid position means the program has violated its own invariant.

Array.create constructs an array with a chosen length and repeats an initial value:

local scores = Array.create<<Int>>(3, 0)

The <<Int>> supplies the generic element type. A negative length traps.

Array elements can be assigned in place:

scores[1] = 10
scores[2] = 20
scores[1] += 5

Indexed assignment is checked and traps if the index is outside the array. Arrays have fixed length: assignment replaces an element but does not append or remove one.

Array.fill(scores, 0) replaces every element with the same value. A compound indexed assignment performs one checked non-optional read, applies the typed operation, and writes the result; the array and index are evaluated once.

Use generalized iteration when the algorithm needs values rather than indexes:

using Pop.Sequence
for score in scores do
print(score)
end

Use an inclusive numeric range when the index itself matters:

for index = 1, Array.length(scores) do
print(Array.get(scores, index))
end

Array<T> remains fixed-length. Use List<T> and Pop.Sequence.collect when the operation needs a growing owned collection; generalized iteration does not resize the source or turn it into a dynamic table.

Arrays are managed by the native runtime. Assigning an array to another local shares the same array; it does not copy every element. Array equality is not defined in this release.