From 0f8219b392e96d3cf7d784ee5d474274169d9918 Mon Sep 17 00:00:00 2001 From: Marmare314 <49279081+Marmare314@users.noreply.github.com> Date: Thu, 6 Apr 2023 15:26:09 +0200 Subject: Unpacking syntax (#532) Closes #341 --- docs/src/reference/scripting.md | 55 ++++++++++++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 14 deletions(-) (limited to 'docs') diff --git a/docs/src/reference/scripting.md b/docs/src/reference/scripting.md index 8f72c219..ca56103c 100644 --- a/docs/src/reference/scripting.md +++ b/docs/src/reference/scripting.md @@ -81,6 +81,41 @@ It explains #name. Sum is #add(2, 3). ``` +Let bindings can be used to destructure arrays and dictionaries. + +```example +#let (x, y) = (1, 2) +The coordinates are #x, #y. + +#let (a, .., b) = (1, 2, 3, 4) +The first element is #a. +The last element is #b. + +#let books = ( + "Shakespeare": "Hamlet", + "Homer": "The Odyssey", + "Austen": "Persuasion", +) +#let (Austen) = books +Austen wrote #Austen. + +#let (Homer: h) = books +Homer wrote #h. + +#let (Homer, ..other) = books +#for (author, title) in other [ + #author wrote #title, +] +``` + +Note that the underscore `_` is the only identifier that can +be used multiple times in the same assignment. + +``` +#let (_, y, _) = (1, 2, 3) +The y coordinate is #y. +``` + ## Conditionals { #conditionals } With a conditional, you can display or compute different things depending on whether some condition is fulfilled. Typst supports `{if}`, `{else if}` and @@ -136,20 +171,12 @@ For loops can iterate over a variety of collections: one cluster.) - `{for value in array {..}}` \ - `{for index, value in array {..}}`\ - Iterates over the items in the [array]($type/array). Can also provide the - index of each item. - -- `{for value in dict {..}}` \ - `{for key, value in dict {..}}` \ - Iterates over the values or keys and values of the - [dictionary]($type/dictionary). - -- `{for value in args {..}}` \ - `{for name, value in args {..}}` \ - Iterates over the values or names and values of the - [arguments]($type/arguments). For positional arguments, the `name` is - `{none}`. + Iterates over the items in the [array]($type/array). The destructuring syntax + described in [Let binding]($scripting/bindings) can also be used here. + +- `{for pair in dict {..}}` \ + Iterates over the key-value pairs of the [dictionary]($type/dictionary). + The pairs can also be destructured by using `{for (key, value) in dict {..}}`. To control the execution of the loop, Typst provides the `{break}` and `{continue}` statements. The former performs an early exit from the loop while -- cgit v1.2.3