From 2735756dbdab1262939a7d852d33b1bea32e784e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C5=99emysl=20Janouch?= Date: Thu, 31 Jul 2014 02:45:04 +0200 Subject: [PATCH] script: add length --- plugins/script | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/plugins/script b/plugins/script index 78e0217..55b35b3 100755 --- a/plugins/script +++ b/plugins/script @@ -910,6 +910,35 @@ defn (fn_to_float) return true; } +// - - Miscellaneous - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +defn (fn_length) +{ + check_stack (1); + struct item *item = pop (ctx); + bool success = true; + switch (item->type) + { + case ITEM_STRING: + push (ctx, new_integer (((struct item_string *) item)->len)); + break; + case ITEM_LIST: + { + long long length = 0; + struct item *iter; + for (iter = get_list (item); iter; iter = iter->next) + length++; + push (ctx, new_integer (length)); + break; + } + default: + ctx->error = strdup ("invalid type"); + success = false; + } + item_free (item); + return success; +} + // - - Stack operations - - - - - - - - - - - - - - - - - - - - - - - - - - - - defn (fn_dup) @@ -1654,7 +1683,6 @@ item_list_to_str (const struct item *script, struct buffer *buf) // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TODO: implement more functions; try to avoid writing it in C -// length -- length of a list/string // -, /, %, ** -- arithmetic // at { value index -- sub-value } -- get n-th subvalue of a string/list @@ -1687,7 +1715,7 @@ init_runtime_library_scripts (void) struct item *script = parse (scripts[i].definition, &error); if (error) { - fprintf (stderr, "error parsing internal script `%s': %s=n", + fprintf (stderr, "error parsing internal script `%s': %s\n", scripts[i].definition, error); free (error); exit (EXIT_FAILURE); @@ -1713,6 +1741,9 @@ init_runtime_library (void) register_handler (">integer", fn_to_integer); register_handler (">float", fn_to_float); + // Miscellaneous + register_handler ("length", fn_length); + // Basic stack manipulation register_handler ("dup", fn_dup); register_handler ("drop", fn_drop);