From a3250864aeb66391abf9add7126912f7676e0195 Mon Sep 17 00:00:00 2001 From: odino Date: Fri, 16 Aug 2019 05:22:45 +0400 Subject: [PATCH] exit() should support a dying message, closes #261 ``` exit(99) exit(99, "I'm gone...") ``` --- docs/types/builtin-function.md | 12 ++++++++++-- evaluator/functions.go | 18 ++++++++++++++++-- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/docs/types/builtin-function.md b/docs/types/builtin-function.md index f6385090..7a4d4a40 100644 --- a/docs/types/builtin-function.md +++ b/docs/types/builtin-function.md @@ -75,14 +75,22 @@ for input in stdin { ... ``` -### exit(code) +### exit(code [, message]) -Exists the script with status `code`: +Exits the script with status `code`: ``` bash exit(99) ``` +You can specify a message that's going to be outputted right +before exiting: + +``` bash +⧐ exit(99, "Got problems...") +Got problems...% +``` + ### rand(max) Returns a random integer number between 0 and `max`: diff --git a/evaluator/functions.go b/evaluator/functions.go index 573ebba2..b72f035c 100644 --- a/evaluator/functions.go +++ b/evaluator/functions.go @@ -396,12 +396,26 @@ func randFn(tok token.Token, args ...object.Object) object.Object { } // exit(code:0) +// exit(code:0, message:"Adios!") func exitFn(tok token.Token, args ...object.Object) object.Object { - err := validateArgs(tok, "exit", args, 1, [][]string{{object.NUMBER_OBJ}}) + var err object.Object + var message string + + if len(args) == 2 { + err = validateArgs(tok, "exit", args, 2, [][]string{{object.NUMBER_OBJ}, {object.STRING_OBJ}}) + message = args[1].(*object.String).Value + } else { + err = validateArgs(tok, "exit", args, 1, [][]string{{object.NUMBER_OBJ}}) + } + if err != nil { return err } + if message != "" { + fmt.Fprintf(globalEnv.Writer, message) + } + arg := args[0].(*object.Number) os.Exit(int(arg.Value)) return arg @@ -715,7 +729,7 @@ func typeFn(tok token.Token, args ...object.Object) object.Object { return &object.String{Token: tok, Value: string(args[0].Type())} } -// split(string:"hello") +// split(string:"hello world!", sep:" ") func splitFn(tok token.Token, args ...object.Object) object.Object { err := validateArgs(tok, "split", args, 2, [][]string{{object.STRING_OBJ}, {object.STRING_OBJ}}) if err != nil {