|
In some projects it's sometime useful to be able to interpret some code dynamically, without any recompile. haXe script is a complete subset of the haXe language. It is dynamically typed but allow allow all haXe expressions apart from type (class,enum,typedef) declarations. InstallIn order to install haXe Script, use haxelib install hscript and compile your program with -lib hscript. There are only three files in hscript : - hscript.Expr : contains enums declarations
- hscript.Parser : a small parser that turns a string into an expression structure (AST)
- hscript.Interp : a small interpreter that execute the AST and returns the latest evaluated value
ExampleHere's a small example of haXe Script usage : var script = "
var sum = 0;
for( a in angles )
sum += Math.cos(a);
sum;
";
var parser = new hscript.Parser();
var program = parser.parseString(script);
var interp = new hscript.Interp();
interp.variables.set("Math",Math); // share the Math class
interp.variables.set("angles",[0,1,2,3]); // set the angles list
trace( interp.execute(program) ); This will calculate the sum of the cosines of the angles given as input. haXe Script has not been really optimized, and it's not meant to be very fast. But it's entirely crossplatform since it's pure haXe code (it doesn't use any platform-specific API). Compared to haXe, limitations are : - no type declarations (classes, enums, typedefs) : only expressions
- no switch construct
- only one variable declaration is allowed in var
- the parser supports optional types for var and function if allowTypes is set, but the interpreter ignore them
- you can enable per-expression position tracking by compiling with -D hscriptPos
|