mirror of
https://github.com/typst/typst
synced 2025-05-14 04:56:26 +08:00
Len function for strings, arrays and dictionaries
This commit is contained in:
parent
2e87808cdd
commit
6967c6c80a
@ -31,6 +31,20 @@ pub fn repr(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `len`: The length of a string, an array or a dictionary.
|
||||||
|
pub fn len(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
|
||||||
|
match args.eat_expect::<Spanned<Value>>(ctx, "collection") {
|
||||||
|
Some(Spanned { v: Value::Str(v), .. }) => Value::Int(v.len() as i64),
|
||||||
|
Some(Spanned { v: Value::Array(v), .. }) => Value::Int(v.len() as i64),
|
||||||
|
Some(Spanned { v: Value::Dict(v), .. }) => Value::Int(v.len() as i64),
|
||||||
|
Some(other) if other.v != Value::Error => {
|
||||||
|
ctx.diag(error!(other.span, "expected string, array or dictionary"));
|
||||||
|
Value::Error
|
||||||
|
}
|
||||||
|
_ => Value::Error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// `rgb`: Create an RGB(A) color.
|
/// `rgb`: Create an RGB(A) color.
|
||||||
///
|
///
|
||||||
/// # Positional parameters
|
/// # Positional parameters
|
||||||
|
@ -56,6 +56,7 @@ pub fn new() -> Scope {
|
|||||||
std.def_func("h", h);
|
std.def_func("h", h);
|
||||||
std.def_func("image", image);
|
std.def_func("image", image);
|
||||||
std.def_func("lang", lang);
|
std.def_func("lang", lang);
|
||||||
|
std.def_func("len", len);
|
||||||
std.def_func("max", max);
|
std.def_func("max", max);
|
||||||
std.def_func("min", min);
|
std.def_func("min", min);
|
||||||
std.def_func("overline", overline);
|
std.def_func("overline", overline);
|
||||||
|
16
tests/typ/utility/basics.typ
Normal file
16
tests/typ/utility/basics.typ
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
// Test basic functions.
|
||||||
|
// Ref: false
|
||||||
|
|
||||||
|
---
|
||||||
|
// Test the `len` function.
|
||||||
|
|
||||||
|
#test(len(()), 0)
|
||||||
|
#test(len(("A", "B", "C")), 3)
|
||||||
|
#test(len("Hello World!"), 12)
|
||||||
|
#test(len((a: 1, b: 2)), 2)
|
||||||
|
|
||||||
|
// Error: 6 missing argument: collection
|
||||||
|
#len()
|
||||||
|
|
||||||
|
// Error: 6-10 expected string, array or dictionary
|
||||||
|
#len(12pt)
|
@ -1,4 +1,4 @@
|
|||||||
// Test basic calculation functions.
|
// Test math functions.
|
||||||
// Ref: false
|
// Ref: false
|
||||||
|
|
||||||
---
|
---
|
Loading…
x
Reference in New Issue
Block a user