Skip to content

Instantly share code, notes, and snippets.

@anissen
Created November 18, 2014 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anissen/cc85af6533f18ddecc59 to your computer and use it in GitHub Desktop.
Save anissen/cc85af6533f18ddecc59 to your computer and use it in GitHub Desktop.
hscript test
haxe -main Test -lib hscript -neko build.n && neko build.n script.hxs
var sum = 0;
for( a in angles )
sum += Math.cos(a);
doStuff(42);
sum;
class Test
{
public static function main() :Void {
var test = new Test();
test.run();
}
public function new() {
}
public function run() {
for (arg in Sys.args()) {
if (!sys.FileSystem.exists(arg)) {
trace('Cannot find script file "$arg"');
continue;
}
trace('Executing script file "$arg"...');
var file = sys.io.File.read(arg, false);
var program = parseScriptFile(file);
if (program != null) {
var result = runScript(program);
trace('Script terminated with value: $result');
}
}
}
public function parseScriptFile(file :haxe.io.Input) :hscript.Expr {
var parser = new hscript.Parser();
try {
return parser.parse(file);
} catch (e :hscript.Expr.Error) {
trace('Parse error at line ${parser.line}: $e');
}
return null;
}
public function doSomeStuff(number :Int) {
trace('doSomeStuff with number: $number');
}
public function runScript(program :hscript.Expr) :Dynamic {
var interp = new hscript.Interp();
interp.variables.set("doStuff", doSomeStuff);
interp.variables.set("Math", Math); // share the Math class
interp.variables.set("angles", [0,1,2,3]); // set the angles list
try {
return interp.execute(program);
} catch (e :hscript.Expr.Error) {
trace('Run-time error: $e');
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment