1 /** 2 This module implements functions for the "console" namespace in the scripting language. 3 4 ──────────────────────────────────────────────────────────────────────────────── 5 6 Copyright (C) 2021 pillager86.rf.gd 7 8 This program is free software: you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation, either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT ANY 14 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 15 PARTICULAR PURPOSE. See the GNU General Public License for more details. 16 17 You should have received a copy of the GNU General Public License along with 18 this program. If not, see <https://www.gnu.org/licenses/>. 19 */ 20 module mildew.stdlib.console; 21 22 import mildew.environment; 23 import mildew.interpreter; 24 import mildew.types; 25 26 /** 27 * Initializes the console library. This is called by Interpreter.initializeStdlib. The console 28 * functions are stored in the "console" global variable and are accessed such as "console.log". 29 * Documentation for these functions can be found at https://pillager86.github.io/dmildew/ 30 * Params: 31 * interpreter = The Interpreter object for which to load the namespace and functions. 32 */ 33 public void initializeConsoleLibrary(Interpreter interpreter) 34 { 35 auto consoleNamespace = new ScriptObject("Console", null); 36 consoleNamespace["log"] = ScriptAny(new ScriptFunction("console.log", &native_console_log)); 37 consoleNamespace["put"] = ScriptAny(new ScriptFunction("console.put", &native_console_put)); 38 consoleNamespace["error"] = ScriptAny(new ScriptFunction("console.error", &native_console_error)); 39 interpreter.forceSetGlobal("console", consoleNamespace, true); 40 } 41 42 private ScriptAny native_console_log(Environment environment, 43 ScriptAny* thisObj, 44 ScriptAny[] args, 45 ref NativeFunctionError nfe) 46 { 47 import std.stdio: write, writeln; 48 if(args.length > 0) 49 write(args[0].toString()); 50 if(args.length > 1) 51 foreach(arg ; args[1..$]) 52 write(" " ~ arg.toString); 53 writeln(); 54 return ScriptAny.UNDEFINED; 55 } 56 57 private ScriptAny native_console_put(Environment environment, 58 ScriptAny* thisObj, 59 ScriptAny[] args, 60 ref NativeFunctionError nfe) 61 { 62 import std.stdio: write, writeln; 63 if(args.length > 0) 64 write(args[0].toString()); 65 if(args.length > 1) 66 foreach(arg ; args[1..$]) 67 write(" " ~ arg.toString); 68 return ScriptAny.UNDEFINED; 69 } 70 71 private ScriptAny native_console_error(Environment environment, 72 ScriptAny* thisObj, 73 ScriptAny[] args, 74 ref NativeFunctionError nfe) 75 { 76 import std.stdio: stderr; 77 foreach(arg ; args) 78 stderr.write(arg.toString ~ " "); 79 stderr.writeln(); 80 return ScriptAny.UNDEFINED; 81 }