summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPřemysl Janouch <p.janouch@gmail.com>2014-07-31 02:45:04 +0200
committerPřemysl Janouch <p.janouch@gmail.com>2014-07-31 02:45:04 +0200
commit2735756dbdab1262939a7d852d33b1bea32e784e (patch)
treee83a9336e0e5b1eeb6cf1eae65a39f73bad2eb00
parentba3f4e620c259c33d0d5da17e89eea922be0e4cd (diff)
downloadxK-2735756dbdab1262939a7d852d33b1bea32e784e.tar.gz
xK-2735756dbdab1262939a7d852d33b1bea32e784e.tar.xz
xK-2735756dbdab1262939a7d852d33b1bea32e784e.zip
script: add length
-rwxr-xr-xplugins/script35
1 files 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);