Arrays
An Array is an ordered collection of values. It holds numbers, strings, or any value, and its indexing is zero-based.
Declaring and creating
Declare with the Array type and assign a literal in square brackets. Elements are separated by commas:
var numeros: Array;
var nomes: Array;
begin
numeros := [10, 20, 30, 40, 50];
nomes := ["Alice", "Bob", "Carlos", "Diana"];
WriteLn("Arrays criados");
end.Arrays criados
An empty array is []:
var vazio: Array;
begin
vazio := [];
WriteLn("Array vazio pronto");
end.Array vazio pronto
Accessing by index
Use array[index] to read an element. The first element is at index 0:
var numeros: Array;
var nomes: Array;
begin
numeros := [10, 20, 30, 40, 50];
nomes := ["Alice", "Bob", "Carlos", "Diana"];
WriteLn("Primeiro número: ", numeros[0]);
WriteLn("Último nome: ", nomes[3]);
end.Primeiro número: 10 Último nome: Diana
Assigning elements
Modify an element with array[i] := value;:
var numeros: Array;
begin
numeros := [10, 20, 30];
numeros[2] := 99;
WriteLn("Terceiro após modificação: ", numeros[2]);
end.Terceiro após modificação: 99
Iterating with for..in
The most direct way to traverse an array is for..in, which hands you each element directly:
var numeros: Array;
var item: Integer;
var soma: Integer;
begin
numeros := [10, 20, 30, 40, 50];
soma := 0;
for item in numeros do
begin
WriteLn(" ", item);
soma := soma + item;
end;
WriteLn("Soma: ", soma);
end.10 20 30 40 50 Soma: 150
It also works with string arrays:
var nomes: Array;
var nome: String;
begin
nomes := ["Alice", "Bob", "Carlos"];
for nome in nomes do
WriteLn("Olá, ", nome, "!");
end.Olá, Alice! Olá, Bob! Olá, Carlos!
Out-of-range indexes
Accessing a nonexistent index throws an error at runtime:
var numeros: Array;
begin
numeros := [10, 20, 30];
WriteLn(numeros[5]); // error: index out of range
end.Out of range is catchable
An out-of-bounds access raises an error that you can wrap in try/catch. See Error handling.
Helper functions
For more advanced operations — sorting, filtering, mapping, summing, concatenating — import the internal.collections library:
uses internal.collections;
var numeros: Array;
begin
numeros := [3, 1, 2];
WriteLn("Tamanho: ", arraySize(numeros));
WriteLn("Soma: ", arraySum(numeros));
end.Tamanho: 3 Soma: 6
Full collections
internal.collections provides arraySort, arrayFilter, arrayMap, arrayReduce, arrayReverse, arrayContains, and much more. See Internal libraries.
Next, learn how to handle runtime failures in Error handling.