List & Loops
PenScript provides functions to work with lists and loops, enabling you to generate arrays, iterate over data, and perform dynamic operations. Below are the key functions for handling lists and loops.
:range
Generates a list of integers from a starting index (index_start
) to an ending index (index_end
), excluding the index_end
.
{
":range": [index_start, index_end]
}
Example:
{
":range": [4, 10]
}
Result: [4, 5, 6, 7, 8, 9]
Use Case: Use :range to create a sequence of numbers for iteration or indexing.
:array :fill
Creates an array of a specified length and optionally fills it using an expression. This allows you to dynamically populate the array with custom data.
{
":array": length,
":fill": {
"label": "Contact person {@position}",
"elements": []
}
}
Example:
{
":array": 5,
":fill": {
"label": "Contact person {@position}",
"elements": []
}
}
Variables Accessible in the :fill Context:
@first:
Boolean, true if it’s the first item.@index
: Current index, starting from 0.@position
: Current position, equals @index + 1.@last
: Boolean, true if it’s the last item.
Use Case: Use :array :fill
to create structured arrays, such as lists of contacts or dynamically generated content.
:map :to
Loops through a list and evaluates an expression for every element in the list. Returns an array containing the evaluated results.
Syntax
{
":map": list,
":to": expression
}
Example 1:
{
":map": ["foo", "bar"],
":to": []
}
Result: Evaluates each element in the list and applies the expression defined in :to.
Example 2 (Advanced):
{
"foo": {
":map": [
{"key1": "foo", "key2": "bar"},
{"key1": "ding", "key2": "dong"}
],
":to": [
"{@item.key1}"
]
}
}
Result: ["foo", "ding"]
The following variables are accessible in the :to
context:
@item
: The content of the current item being evaluated.@first:
Boolean, true if it’s the first item.@index
: Current index, starting from 0.@position
: Current position, equals @index + 1.@last
: Boolean, true if it’s the last item.
Use Case: Use :map :to
for dynamic data transformation, such as extracting specific fields from a list of objects or applying a function to every element in a list.
These list and loop functions provide powerful tools for creating and manipulating arrays, enabling you to build dynamic workflows and handle data efficiently in PenScript.
Updated 6 days ago