summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLeedehai <18319900+Leedehai@users.noreply.github.com>2024-02-02 03:52:58 -0500
committerGitHub <noreply@github.com>2024-02-02 08:52:58 +0000
commitc06a71f653f3b239ace026c1e1966d9d73040c3a (patch)
tree048cffddcabbc0c401ed4cc79ec5ea311d2c0931
parent42f59af812710c27b053acfd038eec0561f70f7b (diff)
Let for-loop iterate Dict with an iterator (#3318)
-rw-r--r--crates/typst/src/eval/flow.rs4
-rw-r--r--crates/typst/src/foundations/cast.rs8
-rw-r--r--docs/reference/scripting.md2
3 files changed, 11 insertions, 3 deletions
diff --git a/crates/typst/src/eval/flow.rs b/crates/typst/src/eval/flow.rs
index 93d6da85..a68be95b 100644
--- a/crates/typst/src/eval/flow.rs
+++ b/crates/typst/src/eval/flow.rs
@@ -145,8 +145,8 @@ impl Eval for ast::ForLoop<'_> {
iter!(for pattern in array);
}
(_, Value::Dict(dict)) => {
- // Iterate over pairs of dict.
- iter!(for pattern in dict.pairs());
+ // Iterate over key-value pairs of dict.
+ iter!(for pattern in dict.iter());
}
(Pattern::Normal(_) | Pattern::Placeholder(_), Value::Str(str)) => {
// Iterate over graphemes of string.
diff --git a/crates/typst/src/foundations/cast.rs b/crates/typst/src/foundations/cast.rs
index cb009912..6a40cecc 100644
--- a/crates/typst/src/foundations/cast.rs
+++ b/crates/typst/src/foundations/cast.rs
@@ -9,7 +9,7 @@ use smallvec::SmallVec;
use unicode_math_class::MathClass;
use crate::diag::{At, SourceResult, StrResult};
-use crate::foundations::{repr, NativeElement, Packed, Repr, Type, Value};
+use crate::foundations::{array, repr, NativeElement, Packed, Repr, Str, Type, Value};
use crate::syntax::{Span, Spanned};
#[rustfmt::skip]
@@ -182,6 +182,12 @@ impl IntoValue for Value {
}
}
+impl IntoValue for (&Str, &Value) {
+ fn into_value(self) -> Value {
+ Value::Array(array![self.0.clone(), self.1.clone()])
+ }
+}
+
impl<T: IntoValue + Clone> IntoValue for Cow<'_, T> {
fn into_value(self) -> Value {
self.into_owned().into_value()
diff --git a/docs/reference/scripting.md b/docs/reference/scripting.md
index 6e64cebb..9a04bfb9 100644
--- a/docs/reference/scripting.md
+++ b/docs/reference/scripting.md
@@ -195,6 +195,8 @@ For loops can iterate over a variety of collections:
- `{for pair in dict {..}}` \
Iterates over the key-value pairs of the [dictionary]($dictionary).
The pairs can also be destructured by using `{for (key, value) in dict {..}}`.
+ It is more efficient than `{for pair in dict.pairs() {..}}` because it doesn't
+ create a temporary array of all key-value pairs.
- `{for letter in "abc" {..}}` \
Iterates over the characters of the [string]($str). Technically, it iterates