-
Notifications
You must be signed in to change notification settings - Fork 0
Lists & loops
Lists are a way to collect elements into a single place. In Pikt, an empty list can be created by calling the listOf(items...)
function:
Now this blue variable holds a list with zero elements. Additional initial elements can be passed as arguments.
In the following example the list contains a 0 and a 1:
New elements can be added later by calling the addToList(list, items...)
function (keep in mind that the magenta pixel in the bottom left corner is a funcall
):
The inverse is given by removeFromList(list, items...)
.
The content of a list (or string) in a certain position can be accessed via the dot
operator using the <list> dot <index>
syntax, where index
is a number, either directly used or stored in a variable.
The following example stores the first element of the list (index 0 ) to a variable :
On the other hand, here we set the first element (previously 0 ) to 1 :
See Accessing fields for further information about the
dot
operator.
The range(start, end)
function can be really handy, especially when working with for loops, as it generates a list of integers from start
up to (or down to) end
, both inclusive.
In this example start
is 0 and end
is 10, so that [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
is generated.
For-each is the only type of loop supported by the language. Its syntax is:
foreach <list> <block>
, where <block>
is a block of code with an optional argument, that starts with lambda.open
and ends with lambda.close
.
The following piece of code prints each element of a list:
foreach <list> lambda.open <argument>
print <argument>
lambda.close
Given that the list is the blue one from the Range example, this is is what the previous pseudocode looks like in Pikt:
The orange pixel is our argument, which goes from 0 to 10 (the contents of the list), and gets printed out.
A break
can be performed on loops by putting two return
statements one next to another. This will exit the loop.
From the previous example:
This will print only the first element in the list before breaking the for-each loop. A break
can be inserted inside nested blocks, such as if
.