From e7410a0be537feeaf8cb798e771366cba627a2e5 Mon Sep 17 00:00:00 2001 From: KingRainbow44 Date: Sun, 13 Aug 2023 18:19:42 -0400 Subject: [PATCH] Semi-functional `require` handler implementation --- .../emu/grasscutter/scripts/ScriptLoader.java | 41 ++++++++++++++----- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/src/main/java/emu/grasscutter/scripts/ScriptLoader.java b/src/main/java/emu/grasscutter/scripts/ScriptLoader.java index b27df74acfa..449b513d5a6 100644 --- a/src/main/java/emu/grasscutter/scripts/ScriptLoader.java +++ b/src/main/java/emu/grasscutter/scripts/ScriptLoader.java @@ -45,17 +45,10 @@ public static synchronized void init() throws Exception { // Lua stuff serializer = new LuaSerializer(); + var ctx = (LuajContext) engine.getContext(); - // Set engine to replace require as a temporary fix to missing scripts - LuajContext ctx = (LuajContext) engine.getContext(); - ctx.globals.set( - "require", - new OneArgFunction() { - @Override - public LuaValue call(LuaValue arg0) { - return LuaValue.ZERO; - } - }); + // Set the 'require' function handler. + ctx.globals.set("require", new RequireFunction()); addEnumByIntValue(ctx, EntityType.values(), "EntityType"); addEnumByIntValue(ctx, QuestState.values(), "QuestState"); @@ -112,6 +105,34 @@ public static Optional tryGet(SoftReference softReference) { } } + static final class RequireFunction extends OneArgFunction { + @Override + public LuaValue call(LuaValue arg) { + // Resolve the script path. + var scriptName = arg.checkjstring(); + var scriptPath = FileUtils.getScriptPath( + "Common/" + scriptName + ".lua"); + + // Load & compile the script. + var script = ScriptLoader.getScript(scriptPath.toString()); + if (script == null) { + return LuaValue.NONE; + } + + // Append the script to the context. + try { + script.eval(); + } catch (Exception exception) { + Grasscutter.getLogger() + .error("Loading script {} failed! - {}", + scriptPath, exception.getLocalizedMessage()); + } + + // TODO: What is the proper return value? + return LuaValue.NONE; + } + } + public static CompiledScript getScript(String path) { var sc = tryGet(scriptsCache.get(path)); if (sc.isPresent()) {