/* * Created by Andrey Cherkashin (acherkashin) * http://acherkashin.me * * License * Copyright (c) 2015 Andrey Cherkashin * The project released under the MIT license: http://opensource.org/licenses/MIT */ package ragefist.core.environment; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.logging.Level; import java.util.logging.Logger; import org.luaj.vm2.LuaClosure; import org.luaj.vm2.LuaTable; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Prototype; import org.luaj.vm2.compiler.LuaC; import ragefist.core.Processor; /** * * @author acherkashin */ public class EnvironmentFunctionCallTask extends EnvironmentCallTask { private static Prototype _prototype = null; static { String script = "do local arg = ...;\n"+ "Processor.addTask(function()\n" + "local fn = util.findFunction(arg[2])\n" + "Processor.onTaskFinish(arg[1], fn and fn(table.unpack(arg[3])))\n" + "end); end;\n"; InputStream stream = new ByteArrayInputStream(script.getBytes(StandardCharsets.UTF_8)); try { _prototype = LuaC.instance.compile(stream, "functionCall"); } catch (IOException ex) { Logger.getLogger(EnvironmentFunctionCallTask.class.getName()).log(Level.SEVERE, null, ex); _prototype = null; } } // ---------------------------------------------------------------------- // // PRIVATE // ---------------------------------------------------------------------- // protected final String _function; protected final LuaTable _args; // ---------------------------------------------------------------------- // // PUBLIC // ---------------------------------------------------------------------- // public EnvironmentFunctionCallTask() { this(null); } public EnvironmentFunctionCallTask(String function) { this(function, null); } public EnvironmentFunctionCallTask(String function, LuaTable args) { super(); setAsync(true); _function = function; _args = args; } @Override public boolean _executeImpl(Processor processor) { EnvironmentProcessor target = (EnvironmentProcessor)processor; LuaValue[] args; if (_args != null) { args = new LuaValue[] { LuaValue.userdataOf(this), LuaValue.valueOf(_function), _args }; } else { args = new LuaValue[] { LuaValue.userdataOf(this), LuaValue.valueOf(_function) }; } LuaClosure f = new LuaClosure(_prototype, target.getGlobals()); f.invoke(LuaTable.listOf(args)); return true; } }