Skip to content

Commit

Permalink
Semi-functional require handler implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
KingRainbow44 committed Aug 13, 2023
1 parent 0175e20 commit e7410a0
Showing 1 changed file with 31 additions and 10 deletions.
41 changes: 31 additions & 10 deletions src/main/java/emu/grasscutter/scripts/ScriptLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -112,6 +105,34 @@ public static <T> Optional<T> tryGet(SoftReference<T> 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()) {
Expand Down

0 comments on commit e7410a0

Please sign in to comment.