summaryrefslogtreecommitdiff
path: root/src/library
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2021-06-18 10:50:08 +0200
committerLaurenz <laurmaedje@gmail.com>2021-06-18 10:50:08 +0200
commit6967c6c80a44186a9aa6ae695cf5caf61d3901fd (patch)
tree14c98ffe740fdddf15af7201b2357ab7b2d82360 /src/library
parent2e87808cdd986dfd91dbbc63fddf74c5b19b2afe (diff)
Len function for strings, arrays and dictionaries
Diffstat (limited to 'src/library')
-rw-r--r--src/library/basic.rs14
-rw-r--r--src/library/mod.rs1
2 files changed, 15 insertions, 0 deletions
diff --git a/src/library/basic.rs b/src/library/basic.rs
index a094f039..333416b4 100644
--- a/src/library/basic.rs
+++ b/src/library/basic.rs
@@ -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.
///
/// # Positional parameters
diff --git a/src/library/mod.rs b/src/library/mod.rs
index 0536eaa1..6c736081 100644
--- a/src/library/mod.rs
+++ b/src/library/mod.rs
@@ -56,6 +56,7 @@ pub fn new() -> Scope {
std.def_func("h", h);
std.def_func("image", image);
std.def_func("lang", lang);
+ std.def_func("len", len);
std.def_func("max", max);
std.def_func("min", min);
std.def_func("overline", overline);