Script Internals

Functionalizing

Note that in the previous script example, sqrt is called with a variable args. When the script is compiled, it is not only placed inside its own module as described previously, but is also wrapped inside its own function. This wrapping function is declared to take a single argument args... which is a tuple of arbitrary size, or more precisely

function _(args...)

And if the module name is for example njIsoMod0, then the complete function would be
invoked as

njIsoMod0._(args...)

which is exactly what script.exec does.

Handling include

The use of include is allowed inside scripts, but because of how the script is isolated and functionalized, special treatment of included files is performed. The default Julia include behavior is supported with 2 modifications.

  1. The include is evaluated local to the isolating module rather than the global main module.
  2. The containing script is transformed and evaluated as if all of the include invocations are hoisted to the top of the file and outside of the functionalized body.

Essentially the following

Consider for example 3 files: f.jl, g.jl, and fg.jl. Where

f.jl

f(x)=x

g.fl

g(x)=f(x)^2

fg.jl

x = args[1];
y = args[2];
z = f(x)*g(y);
include("f.jl");
include("g.jl");
"f*g = $z"

the file f.jl defines the function f and the file g.jl defines the function g, and fg.jl will be included as a script. Assuming the name of the isolating module is named njIsoMod0, the above is essentially the same as

fg.jl transformed

module njIsoMod0

f(x)=x
g(x)=f(x)^2

function _(args...)
   x = args[1];
   y = args[2];
   z = f(x)*g(y);
   "f*g = $z"
end

end

And if fg.jl is scriptified, using the following

var julia = require("node-julia");
var script = julia.Script("fg.jl");

console.log(script.exec(2,3));

The following output is produced

f*g = 18

Note that g.jl depends on f.jl being evaluated first, which is ok as hoisting maintains include order, and that even though the expression z = f(x) * g(x) depends on f(x) and g(x) aready being defined and that the includes of f.jl and g.jl occur after the expression, the include directives are hoisted outside _ and evaluated first.