1 | package tb; |
2 | |
3 | import drjava.util.Tree; |
4 | import net.luaos.tb.common.Solution; |
5 | import org.luaj.vm2.Globals; |
6 | import org.luaj.vm2.LuaTable; |
7 | import org.luaj.vm2.LuaValue; |
8 | import org.luaj.vm2.compiler.LuaC; |
9 | import org.luaj.vm2.lib.jse.JsePlatform; |
10 | |
11 | import java.io.ByteArrayInputStream; |
12 | import java.io.IOException; |
13 | import java.io.InputStream; |
14 | |
15 | public class sol_lua extends Solution { |
16 | String code; |
17 | |
18 | public sol_lua() {} |
19 | |
20 | public sol_lua(String code) { |
21 | this.code = code; |
22 | } |
23 | |
24 | public void fromTree(Tree tree) { |
25 | code = tree.getString(0); |
26 | } |
27 | |
28 | public Tree toTree() { |
29 | return new Tree(this).add(code); |
30 | } |
31 | |
32 | public String compute(String input) { |
33 | return callLuaSolution(createLuaEnvironment(), code, input); |
34 | } |
35 | |
36 | public static String callLuaSolution(LuaTable _G, String code, String input) { |
37 | if (input != null) |
38 | _G.set("input", input); |
39 | |
40 | // compile into a chunk, or load as a class |
41 | InputStream is = new ByteArrayInputStream(code.getBytes()); |
42 | LuaValue chunk = null; |
43 | try { |
44 | chunk = LuaC.instance.load(is, "script", _G); |
45 | } catch (IOException e) { // not gonna happen anyway |
46 | throw new RuntimeException(e); |
47 | } |
48 | |
49 | // Check correct type (probably optional) |
50 | chunk.checkclosure(); |
51 | |
52 | // The chunk can be called with arguments as desired. |
53 | LuaValue result = chunk.call(); |
54 | |
55 | return luaResultToString(result); |
56 | } |
57 | |
58 | public static String luaResultToString(LuaValue result) { |
59 | return result.isnil() ? null : result.toString(); |
60 | } |
61 | |
62 | /** If this is changed, make sure the environment is extendable (not a singleton!) |
63 | * Or change the caller site to make a clone first. */ |
64 | public static LuaTable createLuaEnvironment() { |
65 | // create an environment to run in |
66 | LuaTable _G = new LuaTable(); //JsePlatform.standardGlobals(); |
67 | |
68 | Globals standardGlobals = JsePlatform.standardGlobals(); |
69 | _G.set("_G", _G); |
70 | _G.set("print", standardGlobals.get("print")); |
71 | _G.set("pairs", standardGlobals.get("pairs")); |
72 | return _G; |
73 | } |
74 | } |