1 /** 2 * This module implements functions for the "console" namespace in the scripting language 3 */ 4 module mildew.stdlib.console; 5 6 import mildew.context; 7 import mildew.interpreter; 8 import mildew.types; 9 10 /** 11 * Initializes the console library. This is called by Interpreter.initializeStdlib. The console 12 * functions are stored in the "console" global variable and are accessed such as "console.log" 13 */ 14 public void initializeConsoleLibrary(Interpreter interpreter) 15 { 16 auto consoleNamespace = new ScriptObject("Console", null); 17 consoleNamespace["log"] = ScriptAny(new ScriptFunction("console.log", &native_console_log)); 18 consoleNamespace["put"] = ScriptAny(new ScriptFunction("console.put", &native_console_put)); 19 consoleNamespace["error"] = ScriptAny(new ScriptFunction("console.error", &native_console_error)); 20 interpreter.forceSetGlobal("console", consoleNamespace, true); 21 } 22 23 private ScriptAny native_console_log(Context context, 24 ScriptAny* thisObj, 25 ScriptAny[] args, 26 ref NativeFunctionError nfe) 27 { 28 import std.stdio: write, writeln; 29 if(args.length > 0) 30 write(args[0].toString()); 31 if(args.length > 1) 32 foreach(arg ; args[1..$]) 33 write(" " ~ arg.toString); 34 writeln(); 35 return ScriptAny.UNDEFINED; 36 } 37 38 private ScriptAny native_console_put(Context context, 39 ScriptAny* thisObj, 40 ScriptAny[] args, 41 ref NativeFunctionError nfe) 42 { 43 import std.stdio: write, writeln; 44 if(args.length > 0) 45 write(args[0].toString()); 46 if(args.length > 1) 47 foreach(arg ; args[1..$]) 48 write(" " ~ arg.toString); 49 return ScriptAny.UNDEFINED; 50 } 51 52 private ScriptAny native_console_error(Context context, 53 ScriptAny* thisObj, 54 ScriptAny[] args, 55 ref NativeFunctionError nfe) 56 { 57 import std.stdio: stderr; 58 foreach(arg ; args) 59 stderr.write(arg.toString ~ " "); 60 stderr.writeln(); 61 return ScriptAny.UNDEFINED; 62 }