From 539156430aea44c700e40f25557994ecddae6165 Mon Sep 17 00:00:00 2001 From: Stephen Dolan Date: Sun, 16 Sep 2012 11:08:42 +0100 Subject: [PATCH] Builtin function 'length', for arrays/objects/strings. --- c/builtin.c | 15 +++++++++++++++ c/testdata | 3 +++ 2 files changed, 18 insertions(+) diff --git a/c/builtin.c b/c/builtin.c index 375e3252..39d3f24d 100644 --- a/c/builtin.c +++ b/c/builtin.c @@ -129,6 +129,20 @@ static void f_tonumber(jv input[], jv output[]) { } } +static void f_length(jv input[], jv output[]) { + if (jv_get_kind(input[0]) == JV_KIND_ARRAY) { + output[0] = jv_number(jv_array_length(input[0])); + } else if (jv_get_kind(input[0]) == JV_KIND_OBJECT) { + output[0] = jv_number(jv_object_length(input[0])); + } else if (jv_get_kind(input[0]) == JV_KIND_STRING) { + output[0] = jv_number(jv_string_length(input[0])); + } else { + output[0] = jv_invalid_with_msg(jv_string_fmt("Cannot get the length of %s", + jv_kind_name(jv_get_kind(input[0])))); + jv_free(input[0]); + } +} + struct cfunction function_list[] = { {f_true, "true", CALL_BUILTIN_1_1}, {f_false, "false", CALL_BUILTIN_1_1}, @@ -139,5 +153,6 @@ struct cfunction function_list[] = { {f_divide, "_divide", CALL_BUILTIN_3_1}, {f_tonumber, "tonumber", CALL_BUILTIN_1_1}, {f_equal, "_equal", CALL_BUILTIN_3_1}, + {f_length, "length", CALL_BUILTIN_1_1}, }; struct symbol_table builtins = {function_list, sizeof(function_list)/sizeof(function_list[0])}; diff --git a/c/testdata b/c/testdata index a905d2af..f2eb32a2 100644 --- a/c/testdata +++ b/c/testdata @@ -203,6 +203,9 @@ null [false, false, false, false, false, false, false, true, false] [false, false, false, false, false, false, false, false, true ] +[.[] | length] +[[], {}, [1,2], {"a":42}, "asdf"] +[0, 0, 2, 1, 4] # # User-defined functions