From b7ff127e6b44d7a62623d236be4d1b6db65e8284 Mon Sep 17 00:00:00 2001 From: Pekka Laiho Date: Tue, 8 Dec 2020 17:39:26 +0700 Subject: [PATCH] add function: pstr --- README.md | 3 ++- src/Lib/Core.php | 6 ++++++ src/Printer.php | 7 ++++++- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7555fa7..d5afc8f 100644 --- a/README.md +++ b/README.md @@ -290,7 +290,8 @@ doc | yes | `(doc +)` | `"Return the sum of all arguments."` | Show the docume error | yes | `(error "invalid value")` | `error: invalid value` | Throw an exception with message as argument. exit | no | `(exit 1)` | | Terminate the script with given exit code using [exit](https://www.php.net/manual/en/function.exit.php). loop | yes | `(loop (fn (a) (do (print a) (coinflip))) "hello ")` | `hello hello hello false` | Call the given function repeatedly in a loop until it returns false. -print | no | `(print "hello world")` | `"hello world"null` | Print expression on the screen. Print returns null (which is shown due to the extra print in repl). Give optional second argument as `true` to show strings in readable format. +print | no | `(print "hello world")` | `hello world` | Print expression on the screen. Give optional second argument as `true` to show strings in readable format. Print returns null (shown in REPL). +pstr | yes | `(pstr {"a":"b"} true)` | `"{\"a\":\"b\"}"` | Print expression to string. Give optional second argument as `true` to show strings in readable format. read | no | `(read "(+ 1 2 3)")` | `(+ 1 2 3)` | Read a string as code and return the expression. sleep | no | `(sleep 2000)` | `null` | Sleep for the given period given in milliseconds using [usleep](https://www.php.net/manual/en/function.usleep). timer | no | `(timer (fn (d) (sleep d)) 200)` | `0.20010209` | Measure the execution time of a function and return it in seconds. diff --git a/src/Lib/Core.php b/src/Lib/Core.php index e8ce042..89b0f4b 100644 --- a/src/Lib/Core.php +++ b/src/Lib/Core.php @@ -94,6 +94,12 @@ class Core implements ILib )); } + $env->set('pstr', new CoreFunc('pstr', 'Print argument to string. Give second argument as true to show strings in readable format.', 1, 2, + function ($a, bool $readable = false) { + return $this->printer->pstr($a, $readable); + } + )); + if (!$this->safemode) { $env->set('read', new CoreFunc('read', 'Read string as code.', 1, 1, fn (string $a) => $this->reader->read($this->tokenizer->tokenize($a)) diff --git a/src/Printer.php b/src/Printer.php index 36e2a8a..15d1d20 100644 --- a/src/Printer.php +++ b/src/Printer.php @@ -5,7 +5,12 @@ class Printer { public function print($ast, bool $readable = true): void { - print($this->doPrint($ast, $readable)); + print($this->pstr($ast, $readable)); + } + + public function pstr($ast, bool $readable = true): string + { + return $this->doPrint($ast, $readable); } private function doPrint($a, bool $readable): string