From 90611651d20be931897613680cac4089fb958020 Mon Sep 17 00:00:00 2001 From: IExploitableMan Date: Sun, 22 Feb 2026 23:15:55 +0300 Subject: [PATCH] Implement basic MoonSharp lua scripting --- FodyWeavers.xml | 3 ++- PolyMod.csproj | 1 + src/Loader.cs | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/FodyWeavers.xml b/FodyWeavers.xml index d24cbce..db29f19 100644 --- a/FodyWeavers.xml +++ b/FodyWeavers.xml @@ -3,6 +3,7 @@ Scriban - + MoonSharp.Interpreter + \ No newline at end of file diff --git a/PolyMod.csproj b/PolyMod.csproj index fc5d85d..bf47080 100644 --- a/PolyMod.csproj +++ b/PolyMod.csproj @@ -24,6 +24,7 @@ all + diff --git a/src/Loader.cs b/src/Loader.cs index 838e491..3fb9189 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -16,6 +16,8 @@ using System.Text.RegularExpressions; using UnityEngine; using PolytopiaBackendBase.Common; +using MoonSharp.Interpreter; +using MoonSharp.Interpreter.Interop; namespace PolyMod; @@ -342,6 +344,10 @@ internal static void LoadMods(Dictionary mods, out bool dependencyC { LoadAssemblyFile(mod, file); } + if (Path.GetExtension(file.name) == ".lua") + { + LoadLuaFile(mod, file); + } if (Path.GetFileName(file.name) == "sprites.json") { LoadSpriteInfoFile(mod, file); @@ -509,6 +515,34 @@ public static void LoadAssemblyFile(Mod mod, Mod.File file) } } + /// + /// Loads a lua file from a mod. + /// + /// The mod the assembly belongs to. + /// The assembly file to load. + public static void LoadLuaFile(Mod mod, Mod.File file) + { + UserData.RegistrationPolicy = InteropRegistrationPolicy.Automatic; + Script script = new(); + script.Globals["import"] = (Func)(typeName => + { + var type = AppDomain.CurrentDomain + .GetAssemblies() + .Select(a => a.GetType(typeName)) + .FirstOrDefault(t => t != null); + + if (type == null) + throw new Exception($"Type not found: {typeName}"); + + UserData.RegisterType(type); + + return UserData.CreateStatic(type); + }); + script.DoString(Encoding.UTF8.GetString(file.bytes)); + DynValue load = script.Globals.Get("load"); + script.Call(load); + } + /// /// Loads a localization file from a mod. ///