Embed JavaScript into D

Adam D. Ruppe destructionator at gmail.com
Mon Nov 4 13:20:46 PST 2013


On Monday, 4 November 2013 at 19:35:55 UTC, Jeroen Bollen wrote:
> Is there a way I can embed javascript into my D application?

You could use any C javascript lib too, but for ones already 
wrapped or something, I know there's a few D implementations of 
javascript: dmdscript 
<http://www.digitalmars.com/dscript/index.html> (written in D1 
but there's two or three ports out there to D2), an experimental 
implementation by Maxime Chevalier-Boisvert 
<http://dconf.org/talks/chevalier_boisvert.html>, and I think a 
couple more.

I also wrote a language that is kinda like javascript but isn't 
actually the same and is buggy... but might be easier to integrate
https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff

get script.d and jsvar.d, don't need the other files.

usage:

import arsd.jsvar;
import arsd.script;

void main() {
     var globals = var.emptyObject;

     // add a variadic write function...
     globals.write._function = (var _this, var[] args) {
         import std.conv;
         import std.stdio;
	string s;
	foreach(a; args)
		s ~= a.get!string;
	writeln(s);
	return var(null);
     };

     // you can also add D functions pretty straightforwardly
     globals.otherFunction = (int a, int b) {
        return a+b;
     };

     // can also set values easily in D
     globals.yourValue = 10;

     import std.file;
     // read the user's code file
     interpret(readText("scriptcode.js"), globals);
     /*
          // suppose the code there is:
          // the syntax is kinda like javascript and kinda like D
          // the concat operator is D style, but function decls 
are JS style
          function foo(name) { return "hello, " ~ name; }
          // set a global variable too
          var myname = "adam"; // my language requires variables 
be declared, even if global
     */

     // and functions/variable set in the script code are also 
available via the globals object

     // extra parens are needed to call script funs because D's 
@property is broken
     auto message = globals.foo()(globals.myname); // calls the 
script function with a script variable
     import std.stdio;
     writeln(message); // write what the script returned
     globals.write()(globals.foo()("D code")); // can also call it 
with D variables/data
}



If you use my little language, you'll probably find bugs, but I 
think it is about as easy as you can get when interfacing with D: 
the jsvar module gives you a var type, in D, that works very 
similarly to the javascript style var in the script language 
(except the double parens needed when calling a function) so the 
line can be easily blurred between native and script functions, 
as you see here.

Compile easily too:

dmd yourfile.d jsvar.d script.d


More information about the Digitalmars-d-learn mailing list