From 783dccf53dcf0ab67dc3a11cdcff7df52953a36a Mon Sep 17 00:00:00 2001 From: szy73711 Date: Mon, 30 Nov 2026 02:42:51 +0800 Subject: [PATCH] feat: upgrade to ts2lua-unreal v0.3.0 and refactor Game classes to pure C++ callback + TS composition hot-reload --- Script/lua/Framework/Bootstrap.lua | 40 +- Script/lua/Framework/EventBus.lua | 25 +- Script/lua/Framework/HotReload.lua | 115 ++-- Script/lua/Framework/Log.lua | 5 +- Script/lua/Game/LuaCharacter.lua | 17 +- Script/lua/Game/LuaDemoActor.lua | 300 ++++++-- Script/lua/Game/LuaGameInstance.lua | 19 +- Script/lua/Game/LuaGameMode.lua | 21 +- Script/lua/Game/LuaPlayerController.lua | 29 +- Script/lua/Lib/Class.lua | 53 ++ Script/lua/Lib/Module.lua | 649 ++++++++++++++++++ .../Tests/Extra/HotReloadAndFrameworkTest.lua | 63 +- .../Tests/Extra/LifecycleAndMemoryTest.lua | 44 +- .../lua/Tests/Extra/LifecycleSafetyActor.lua | 2 +- Script/lua/Tests/Extra/Lua54PitfallsTest.lua | 25 +- Script/lua/Tests/Gameplay/BehaviorTree.lua | 19 +- .../Tests/Gameplay/BuffAndAttributeSystem.lua | 9 +- .../Tests/Gameplay/CoroutineTaskRunner.lua | 9 +- Script/lua/Tests/Gameplay/FSM.lua | 9 +- Script/lua/Tests/Gameplay/GameplaySuite.lua | 89 ++- Script/lua/Tests/Gameplay/InventorySystem.lua | 9 +- Script/lua/Tests/Gameplay/ObjectPool.lua | 9 +- Script/lua/Tests/Gameplay/TimerScheduler.lua | 11 +- Script/lua/Tests/Harness/MockUnLuaRuntime.lua | 5 +- Script/lua/Tests/Harness/TestRunner.lua | 5 +- Script/lua/Tests/RunAllTests.lua | 63 +- .../Tests/Syntax/BasicTypesAndControlFlow.lua | 31 +- .../Syntax/FunctionsClosuresAndTuples.lua | 28 +- .../Tests/Syntax/PureClassesAndGenerics.lua | 32 +- Script/lua/Tests/Syntax/UnLuaSyntaxSuite.lua | 33 +- Script/lua/Tests/UE/UERuntimeSuite.lua | 150 +++- .../UnLuaExamples/Ex06_NativeContainers.lua | 22 +- .../UnLuaExamples/UnLuaExamplesSuite.lua | 62 +- Script/lua/lualib_bundle.lua | 22 +- Script/ts/package-lock.json | 6 +- Script/ts/package.json | 2 +- Script/ts/scripts/run-tests.mjs | 6 +- Script/ts/src/Framework/Bootstrap.ts | 6 +- Script/ts/src/Framework/EventBus.ts | 1 + Script/ts/src/Framework/HotReload.ts | 91 +-- Script/ts/src/Game/LuaCharacter.ts | 15 +- Script/ts/src/Game/LuaDemoActor.ts | 275 ++++++-- Script/ts/src/Game/LuaGameInstance.ts | 19 +- Script/ts/src/Game/LuaGameMode.ts | 31 +- Script/ts/src/Game/LuaPlayerController.ts | 31 +- .../Tests/Extra/HotReloadAndFrameworkTest.ts | 18 +- Script/ts/src/Tests/UE/UERuntimeSuite.ts | 74 +- Script/ts/types/project.d.ts | 6 + .../UnrealLuaDemo/Core/LuaCallbackBridge.cpp | 186 +++++ Source/UnrealLuaDemo/Core/LuaCallbackBridge.h | 21 + Source/UnrealLuaDemo/Core/LuaCharacter.cpp | 12 +- Source/UnrealLuaDemo/Core/LuaCharacter.h | 8 +- Source/UnrealLuaDemo/Core/LuaGameInstance.cpp | 8 +- Source/UnrealLuaDemo/Core/LuaGameInstance.h | 8 +- Source/UnrealLuaDemo/Core/LuaGameModeBase.cpp | 12 +- Source/UnrealLuaDemo/Core/LuaGameModeBase.h | 8 +- .../Core/LuaPlayerController.cpp | 18 +- .../UnrealLuaDemo/Core/LuaPlayerController.h | 21 +- Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp | 20 +- Source/UnrealLuaDemo/Demo/LuaDemoActor.h | 15 +- .../HotUpdate/LuaHotUpdateSubsystem.cpp | 127 +++- .../HotUpdate/LuaHotUpdateSubsystem.h | 7 + Source/UnrealLuaDemo/UnrealLuaDemo.cpp | 2 +- .../RunLuaTestsCommandlet.cpp | 4 +- 64 files changed, 2368 insertions(+), 714 deletions(-) create mode 100644 Script/lua/Lib/Class.lua create mode 100644 Script/lua/Lib/Module.lua create mode 100644 Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp create mode 100644 Source/UnrealLuaDemo/Core/LuaCallbackBridge.h diff --git a/Script/lua/Framework/Bootstrap.lua b/Script/lua/Framework/Bootstrap.lua index 476dedb..e65e1c4 100644 --- a/Script/lua/Framework/Bootstrap.lua +++ b/Script/lua/Framework/Bootstrap.lua @@ -1,7 +1,7 @@ -local ____exports = {} -local Log = require("Framework.Log") -local EventBus = require("Framework.EventBus") -local HotReload = require("Framework.HotReload") +local ____exports = __module.env +local Log = __MODULE__.Import("Framework.Log", __module) +local EventBus = __MODULE__.Import("Framework.EventBus", __module) +local HotReload = __MODULE__.Import("Framework.HotReload", __module) function ____exports.Shutdown() Log.Info("Lua GameFramework shutting down...") EventBus.Clear() @@ -9,8 +9,12 @@ function ____exports.Shutdown() ____exports.IsInitialized = false _G.GameFramework = nil end -____exports.Version = "0.1.0" +____exports.Version = "0.2.0" +--- +-- @module_data ____exports.IsInitialized = false +--- +-- @module_data ____exports.GameInstance = nil function ____exports.Init(gameInstance) ____exports.GameInstance = gameInstance @@ -24,4 +28,28 @@ function ____exports.Init(gameInstance) } Log.Info("Lua GameFramework initialized (version=%s, Lua=%s)", ____exports.Version, _VERSION) end -return ____exports +function __module.StashData(env, to) + local ____has = to.__has__ + if not ____has then + ____has = {} + to.__has__ = ____has + end + to.IsInitialized = ____exports.IsInitialized + ____has.IsInitialized = true + to.GameInstance = ____exports.GameInstance + ____has.GameInstance = true +end +function __module.RestoreData(env, from) + local ____has = from.__has__ + if not ____has then + return + end + if ____has.IsInitialized then + ____exports.IsInitialized = from.IsInitialized + end + if ____has.GameInstance then + ____exports.GameInstance = from.GameInstance + end +end +function __module.UpdateImports() +end diff --git a/Script/lua/Framework/EventBus.lua b/Script/lua/Framework/EventBus.lua index fc3a227..6f4a109 100644 --- a/Script/lua/Framework/EventBus.lua +++ b/Script/lua/Framework/EventBus.lua @@ -1,4 +1,6 @@ -local ____exports = {} +local ____exports = __module.env +--- +-- @module_data local Listeners = {} function ____exports.On(eventName, callback, owner) assert( @@ -98,4 +100,23 @@ end function ____exports.Clear() Listeners = {} end -return ____exports +function __module.StashData(env, to) + local ____has = to.__has__ + if not ____has then + ____has = {} + to.__has__ = ____has + end + to.Listeners = Listeners + ____has.Listeners = true +end +function __module.RestoreData(env, from) + local ____has = from.__has__ + if not ____has then + return + end + if ____has.Listeners then + Listeners = from.Listeners + end +end +function __module.UpdateImports() +end diff --git a/Script/lua/Framework/HotReload.lua b/Script/lua/Framework/HotReload.lua index 16af565..e38c272 100644 --- a/Script/lua/Framework/HotReload.lua +++ b/Script/lua/Framework/HotReload.lua @@ -1,97 +1,76 @@ -local ____exports = {} -local Log = require("Framework.Log") -local EventBus = require("Framework.EventBus") +local ____exports = __module.env +local Log = __MODULE__.Import("Framework.Log", __module) +local EventBus = __MODULE__.Import("Framework.EventBus", __module) ____exports.EVENT_BEFORE_RELOAD = "Framework.BeforeHotReload" ____exports.EVENT_AFTER_RELOAD = "Framework.AfterHotReload" -local function GetLuaPackage() - return _G.package -end -local function CollectReloadableGameModules() +local function CollectLoadedHotReloadModules() local modules = {} - for name in pairs(GetLuaPackage().loaded) do - if type(name) == "string" and (string.match(name, "^Game%.")) ~= nil then + if __MODULE__ == nil then + return modules + end + for name in pairs(__MODULE__.AllLoadedModules()) do + if type(name) == "string" and name ~= "Framework.HotReload" and ((string.match(name, "^Game%.")) ~= nil or (string.match(name, "^Framework%.")) ~= nil) then modules[#modules + 1] = name end end table.sort(modules) return modules end ---- Reloads a specific Lua module using UnLua's hot-reload sandbox (falls back to package.loaded reset). +--- 单文件热更指定模块(完全基于 Lib/Module.lua 的 __MODULE__.ReimportSafely,零入侵 UnLua)。 function ____exports.ReloadModule(moduleName) if type(moduleName) ~= "string" or moduleName == "" then return false, "Invalid module name" end - Log.Info("Hot-reloading Lua module: %s", moduleName) + if __MODULE__ == nil then + return false, "__MODULE__ runtime is not initialized" + end + if __MODULE__.GetModuleByName(moduleName) == nil then + Log.Warn("Module '%s' is not loaded yet, skipping hot-reload.", moduleName) + return false, "Module not loaded: " .. moduleName + end + Log.Info("Hot-reloading module via __MODULE__: %s", moduleName) EventBus.Emit(____exports.EVENT_BEFORE_RELOAD, moduleName) - local okHr, unluaHr = pcall(require, "UnLua.HotReload") - local hrMod = unluaHr - if okHr and hrMod ~= nil and type(hrMod.reload) == "function" then - local ok, err = pcall(hrMod.reload, {moduleName}) - if not ok then - Log.Error( - "UnLua.HotReload.reload('%s') failed: %s", - moduleName, - tostring(err) - ) - return false, err - end - else - GetLuaPackage().loaded[moduleName] = nil - local ok, result = pcall(require, moduleName) - if not ok then - Log.Error( - "Failed to hot-reload module '%s': %s", - moduleName, - tostring(result) - ) - return false, result - end + local ok, err = __MODULE__.ReimportSafely(moduleName) + if not ok then + Log.Error( + "__MODULE__.ReimportSafely('%s') failed: %s", + moduleName, + tostring(err) + ) + return false, err end EventBus.Emit(____exports.EVENT_AFTER_RELOAD, moduleName) - Log.Info("Successfully hot-reloaded Lua module: %s", moduleName) + Log.Info("Successfully hot-reloaded module: %s", moduleName) return true end ---- Triggers UnLua hot-reload across all loaded Game.* modules (supports Saved/HotUpdate/Script overrides). +--- 批量热更所有已加载的业务/框架模块(Game.* / Framework.*)。 function ____exports.ReloadAll() - local gameModules = CollectReloadableGameModules() - Log.Info("Triggering UnLua HotReload (modules=%d)...", #gameModules) + local managedModules = CollectLoadedHotReloadModules() + Log.Info("Triggering HotReload via __MODULE__ (modules=%d)...", #managedModules) EventBus.Emit(____exports.EVENT_BEFORE_RELOAD, "*") - local okHr, unluaHr = pcall(require, "UnLua.HotReload") - local hrMod = unluaHr - if okHr and hrMod ~= nil and type(hrMod.reload) == "function" then - if #gameModules > 0 then - local ok, err = pcall(hrMod.reload, gameModules) + local allOk = true + do + local i = 0 + while i < #managedModules do + local modName = managedModules[i + 1] + local ok, err = __MODULE__.ReimportSafely(modName) if not ok then Log.Error( - "UnLua.HotReload.reload(gameModules) failed: %s", + "__MODULE__.ReimportSafely('%s') failed: %s", + modName, tostring(err) ) - return false + allOk = false end + i = i + 1 end - local ok2, err2 = pcall(hrMod.reload) - if not ok2 then - Log.Error( - "UnLua.HotReload.reload() failed: %s", - tostring(err2) - ) - return false - end - elseif UnLua ~= nil and type(UnLua.HotReload) == "function" then - local ok, err = pcall(UnLua.HotReload) - if not ok then - Log.Error( - "UnLua.HotReload() failed: %s", - tostring(err) - ) - return false - end - else - Log.Warn("UnLua.HotReload is unavailable; skipping global hot reload.") - return false end EventBus.Emit(____exports.EVENT_AFTER_RELOAD, "*") - Log.Info("UnLua HotReload completed.") - return true + Log.Info( + "HotReload completed (ok=%s).", + tostring(allOk) + ) + return allOk +end +function __module.UpdateImports() end -return ____exports diff --git a/Script/lua/Framework/Log.lua b/Script/lua/Framework/Log.lua index c9ca990..333cdd8 100644 --- a/Script/lua/Framework/Log.lua +++ b/Script/lua/Framework/Log.lua @@ -1,4 +1,4 @@ -local ____exports = {} +local ____exports = __module.env --- -- @noSelfInFile local TAG = "[UnrealLuaDemo]" @@ -27,4 +27,5 @@ end function ____exports.Error(fmt, ...) print(FormatMessage("ERROR", fmt, ...)) end -return ____exports +function __module.UpdateImports() +end diff --git a/Script/lua/Game/LuaCharacter.lua b/Script/lua/Game/LuaCharacter.lua index 840482b..f2d0447 100644 --- a/Script/lua/Game/LuaCharacter.lua +++ b/Script/lua/Game/LuaCharacter.lua @@ -1,12 +1,13 @@ -local Log = require("Framework.Log") -local LuaCharacter = UnLua.Class() -function LuaCharacter.ReceiveBeginPlay(self) - Log.Info("LuaCharacter:ReceiveBeginPlay()") +local ____exports = __module.env +local Log = __MODULE__.Import("Framework.Log", __module) +function ____exports.OnBeginPlay(_character) + Log.Info("LuaCharacter.OnBeginPlay()") end -function LuaCharacter.ReceiveEndPlay(self, EndPlayReason) +function ____exports.OnEndPlay(_character, endPlayReason) Log.Info( - "LuaCharacter:ReceiveEndPlay(reason=%s)", - tostring(EndPlayReason) + "LuaCharacter.OnEndPlay(reason=%s)", + tostring(endPlayReason) ) end -return LuaCharacter +function __module.UpdateImports() +end diff --git a/Script/lua/Game/LuaDemoActor.lua b/Script/lua/Game/LuaDemoActor.lua index 72b5851..406a373 100644 --- a/Script/lua/Game/LuaDemoActor.lua +++ b/Script/lua/Game/LuaDemoActor.lua @@ -1,7 +1,15 @@ -local Log = require("Framework.Log") -local EventBus = require("Framework.EventBus") -local HotReload = require("Framework.HotReload") -local DEMO_COLORS = { +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local Log = __MODULE__.Import("Framework.Log", __module) +local EventBus = __MODULE__.Import("Framework.EventBus", __module) +local HotReload = __MODULE__.Import("Framework.HotReload", __module) +local globalPingCount, globalReloadCount +____exports.DEMO_VERSION = "v1" +--- 目标旋转速度(度/秒,直接驱动方块自转速度,热更后下一帧立即生效) +____exports.ACTOR_SPIN_SPEED = 60 +--- 当前展示配色(热更修改颜色值与名称后,__module.OnReimport 立即刷新方块材质与 3D 文本) +____exports.DEMO_COLORS = { { Name = "Cyan", R = 0.08, @@ -43,24 +51,60 @@ local DEMO_COLORS = { local function MakeLinearColor(c) return UE.FLinearColor(c.R, c.G, c.B, c.A) end -local LuaDemoActor = UnLua.Class() -function LuaDemoActor.ReceiveBeginPlay(self) - self.ElapsedTime = 0 - self.TextRefreshTimer = 0 - self.TickCount = 0 - self.PingCount = 0 - self.ReloadCount = 0 - self.ColorIndex = 0 - self.HasLoggedTick = false +--- +-- @noSelf +local function IsActorAlive(actor) + if actor == nil then + return false + end + if UE ~= nil and UE.UKismetSystemLibrary ~= nil and UE.UKismetSystemLibrary.IsValid ~= nil then + return UE.UKismetSystemLibrary.IsValid(actor) + end + return true +end +____exports.DemoActorController = __TS__DefineClass("DemoActorController", __module) +local DemoActorController = ____exports.DemoActorController +DemoActorController.name = "DemoActorController" +function DemoActorController.prototype.____constructor(self, actor) + self.elapsedTime = 0 + self.textRefreshTimer = 0 + self.tickCount = 0 + self.pingCount = 0 + self.reloadCount = 0 + self.colorIndex = 0 + self.hasLoggedTick = false + self.actor = actor self._tmpDeltaRot = UE.FRotator(0, 0, 0) +end +function DemoActorController.prototype.IsValid(self) + return IsActorAlive(self.actor) +end +function DemoActorController.prototype.GetSpinSpeed(self) + return ____exports.ACTOR_SPIN_SPEED +end +function DemoActorController.prototype.GetCurrentColor(self) + return ____exports.DEMO_COLORS[self.colorIndex + 1] or ____exports.DEMO_COLORS[1] +end +function DemoActorController.prototype.OnBeginPlay(self) EventBus.On("Demo.Ping", self.OnDemoPing, self) EventBus.On(HotReload.EVENT_AFTER_RELOAD, self.OnAfterHotReload, self) self:ApplyCurrentColor() self:RefreshStatusText() - Log.Info("LuaDemoActor:ReceiveBeginPlay() bound successfully! Lua=%s", _VERSION) - local msg = string.format("[UnLua Demo] LuaDemoActor active (%s) - Press [Space] to Ping, [R] to HotReload", _VERSION) + Log.Info( + "LuaDemoActor.OnBeginPlay() ready! version=%s speed=%.1f color=%s Lua=%s", + ____exports.DEMO_VERSION, + self:GetSpinSpeed(), + self:GetCurrentColor().Name, + _VERSION + ) + local msg = string.format( + "[UnLua Demo] Pure-TS Actor active (%s | Speed=%.0f | Color=%s) - [Space] Ping, [R] HotReload", + ____exports.DEMO_VERSION, + self:GetSpinSpeed(), + self:GetCurrentColor().Name + ) UE.UKismetSystemLibrary.PrintString( - self, + self.actor, msg, true, true, @@ -68,45 +112,47 @@ function LuaDemoActor.ReceiveBeginPlay(self) 8 ) end -function LuaDemoActor.ReceiveTick(self, DeltaSeconds) - self.ElapsedTime = (self.ElapsedTime or 0) + DeltaSeconds - self.TickCount = (self.TickCount or 0) + 1 - if not self.HasLoggedTick then - self.HasLoggedTick = true - Log.Info("LuaDemoActor:ReceiveTick() first tick verified (dt=%.4f)", DeltaSeconds) +function DemoActorController.prototype.OnTick(self, deltaSeconds) + self.elapsedTime = self.elapsedTime + deltaSeconds + self.tickCount = self.tickCount + 1 + if not self.hasLoggedTick then + self.hasLoggedTick = true + Log.Info( + "LuaDemoActor.OnTick() first tick verified (dt=%.4f, speed=%.1f)", + deltaSeconds, + self:GetSpinSpeed() + ) end - local yawDelta = (self.SpinSpeed or 60) * DeltaSeconds + local yawDelta = self:GetSpinSpeed() * deltaSeconds local pitchDelta = yawDelta * 0.35 - if not self._tmpDeltaRot then - self._tmpDeltaRot = UE.FRotator(pitchDelta, yawDelta, 0) - else - self._tmpDeltaRot.Pitch = pitchDelta - self._tmpDeltaRot.Yaw = yawDelta - self._tmpDeltaRot.Roll = 0 - end - self:AddCubeLocalRotation(self._tmpDeltaRot) - local zOffset = math.sin(self.ElapsedTime * (self.BobFrequency or 2)) * (self.BobAmplitude or 25) - self:SetCubeVerticalOffset(zOffset) - self.TextRefreshTimer = (self.TextRefreshTimer or 0) + DeltaSeconds - if self.TextRefreshTimer >= 0.2 then - self.TextRefreshTimer = 0 + self._tmpDeltaRot.Pitch = pitchDelta + self._tmpDeltaRot.Yaw = yawDelta + self._tmpDeltaRot.Roll = 0 + self.actor:AddCubeLocalRotation(self._tmpDeltaRot) + local zOffset = math.sin(self.elapsedTime * (self.actor.BobFrequency or 2)) * (self.actor.BobAmplitude or 25) + self.actor:SetCubeVerticalOffset(zOffset) + self.textRefreshTimer = self.textRefreshTimer + deltaSeconds + if self.textRefreshTimer >= 0.2 then + self.textRefreshTimer = 0 self:RefreshStatusText() end end -function LuaDemoActor.OnDemoPing(self, sourceName) - self.PingCount = (self.PingCount or 0) + 1 - self.ColorIndex = ((self.ColorIndex or 0) + 1) % #DEMO_COLORS +function DemoActorController.prototype.OnDemoPing(self, sourceName) + self.pingCount = self.pingCount + 1 + globalPingCount = globalPingCount + 1 + self.colorIndex = (self.colorIndex + 1) % #____exports.DEMO_COLORS local colorEntry = self:ApplyCurrentColor() self:RefreshStatusText() local msg = string.format( - "[UnLua Demo] Ping #%d from %s -> Cube color: %s", - self.PingCount, + "[UnLua Demo] Ping #%d from %s -> Cube color: %s (Speed=%.0f)", + self.pingCount, tostring(sourceName), - colorEntry.Name + colorEntry.Name, + self:GetSpinSpeed() ) Log.Info(msg) UE.UKismetSystemLibrary.PrintString( - self, + self.actor, msg, true, true, @@ -114,17 +160,22 @@ function LuaDemoActor.OnDemoPing(self, sourceName) 3 ) end -function LuaDemoActor.OnAfterHotReload(self, moduleName) - self.ReloadCount = (self.ReloadCount or 0) + 1 +function DemoActorController.prototype.OnAfterHotReload(self, moduleName) + self.reloadCount = self.reloadCount + 1 + globalReloadCount = globalReloadCount + 1 + self:ApplyCurrentColor() self:RefreshStatusText() local msg = string.format( - "[UnLua Demo] HotReload #%d completed (target=%s)", - self.ReloadCount, - tostring(moduleName) + "[UnLua Demo] HotReload #%d applied! target=%s | version=%s | Speed=%.0f | Color=%s", + self.reloadCount, + tostring(moduleName), + ____exports.DEMO_VERSION, + self:GetSpinSpeed(), + self:GetCurrentColor().Name ) Log.Info(msg) UE.UKismetSystemLibrary.PrintString( - self, + self.actor, msg, true, true, @@ -132,25 +183,148 @@ function LuaDemoActor.OnAfterHotReload(self, moduleName) 4 ) end -function LuaDemoActor.ApplyCurrentColor(self) - local colorEntry = DEMO_COLORS[(self.ColorIndex or 0) + 1] or DEMO_COLORS[1] - self:SetCubeColor(MakeLinearColor(colorEntry)) +function DemoActorController.prototype.ResetToPrimaryColor(self) + self.colorIndex = 0 +end +function DemoActorController.prototype.ApplyCurrentColor(self) + local colorEntry = self:GetCurrentColor() + self.actor:SetCubeColor(MakeLinearColor(colorEntry)) return colorEntry end -function LuaDemoActor.RefreshStatusText(self) - local colorEntry = DEMO_COLORS[(self.ColorIndex or 0) + 1] or DEMO_COLORS[1] +function DemoActorController.prototype.RefreshStatusText(self) + local colorEntry = self:GetCurrentColor() local text = string.format( - "UnLua Active (%s)\nTime: %.1fs | Pings: %d | Reloads: %d | Color: %s\n[Space] Ping Lua | [R] HotReload", + "Pure-TS Actor (%s | %s)\nSpeed: %.0f deg/s | Color: %s\nTime: %.1fs | Pings: %d | Reloads: %d\n[Space] Ping | [R] HotReload", _VERSION, - self.ElapsedTime or 0, - self.PingCount or 0, - self.ReloadCount or 0, - colorEntry.Name + ____exports.DEMO_VERSION, + self:GetSpinSpeed(), + colorEntry.Name, + self.elapsedTime, + self.pingCount, + self.reloadCount ) - self:SetStatusText(text) + self.actor:SetStatusText(text) end -function LuaDemoActor.ReceiveEndPlay(self, EndPlayReason) +function DemoActorController.prototype.OnEndPlay(self, _endPlayReason) EventBus.OffAllForOwner(self) - Log.Info("LuaDemoActor:ReceiveEndPlay(ticks=%d, pings=%d)", self.TickCount or 0, self.PingCount or 0) + Log.Info("LuaDemoActor.OnEndPlay(ticks=%d, pings=%d)", self.tickCount, self.pingCount) +end +--- +-- @module_data +local activeControllers = {} +--- +-- @module_data +globalPingCount = 0 +--- +-- @module_data +globalReloadCount = 0 +--- +-- @noSelf +local function GetActorKey(actor) + if actor.GetName ~= nil then + return actor:GetName() + end + return tostring(actor) +end +--- +-- @noSelf +function ____exports.OnBeginPlay(actor) + local key = GetActorKey(actor) + local old = activeControllers[key] + if old ~= nil then + old:OnEndPlay(0) + end + local ctrl = __TS__New(____exports.DemoActorController, actor) + activeControllers[key] = ctrl + ctrl:OnBeginPlay() +end +--- +-- @noSelf +function ____exports.OnTick(actor, deltaSeconds) + local ctrl = activeControllers[GetActorKey(actor)] + if ctrl ~= nil then + ctrl:OnTick(deltaSeconds) + end +end +--- +-- @noSelf +function ____exports.OnEndPlay(actor, endPlayReason) + local key = GetActorKey(actor) + local ctrl = activeControllers[key] + if ctrl ~= nil then + ctrl:OnEndPlay(endPlayReason) + activeControllers[key] = nil + end +end +--- +-- @noSelf +function ____exports.GetGlobalStats() + return { + pings = globalPingCount, + reloads = globalReloadCount, + version = ____exports.DEMO_VERSION, + spinSpeed = ____exports.ACTOR_SPIN_SPEED, + primaryColor = ____exports.DEMO_COLORS[1].Name + } +end +--- +-- @noSelf +function ____exports.GetActiveControllerCount() + local count = 0 + for _, ctrl in pairs(activeControllers) do + if ctrl ~= nil then + count = count + 1 + end + end + return count +end +__module.OnReimport = function() + for key, ctrl in pairs(activeControllers) do + if ctrl ~= nil then + if ctrl:IsValid() then + ctrl:ResetToPrimaryColor() + ctrl:ApplyCurrentColor() + ctrl:RefreshStatusText() + else + activeControllers[key] = nil + end + end + end + Log.Info( + "Game.LuaDemoActor OnReimport applied! version=%s speed=%.1f color=%s activeActors=%d", + ____exports.DEMO_VERSION, + ____exports.ACTOR_SPIN_SPEED, + ____exports.DEMO_COLORS[1].Name, + ____exports.GetActiveControllerCount() + ) +end +function __module.StashData(env, to) + local ____has = to.__has__ + if not ____has then + ____has = {} + to.__has__ = ____has + end + to.activeControllers = activeControllers + ____has.activeControllers = true + to.globalPingCount = globalPingCount + ____has.globalPingCount = true + to.globalReloadCount = globalReloadCount + ____has.globalReloadCount = true +end +function __module.RestoreData(env, from) + local ____has = from.__has__ + if not ____has then + return + end + if ____has.activeControllers then + activeControllers = from.activeControllers + end + if ____has.globalPingCount then + globalPingCount = from.globalPingCount + end + if ____has.globalReloadCount then + globalReloadCount = from.globalReloadCount + end +end +function __module.UpdateImports() end -return LuaDemoActor diff --git a/Script/lua/Game/LuaGameInstance.lua b/Script/lua/Game/LuaGameInstance.lua index d09d32e..073bdc8 100644 --- a/Script/lua/Game/LuaGameInstance.lua +++ b/Script/lua/Game/LuaGameInstance.lua @@ -1,12 +1,13 @@ -local Bootstrap = require("Framework.Bootstrap") -local Log = require("Framework.Log") -local LuaGameInstance = UnLua.Class() -function LuaGameInstance.ReceiveInit(self) - Bootstrap.Init(self) - Log.Info("LuaGameInstance:ReceiveInit()") +local ____exports = __module.env +local Bootstrap = __MODULE__.Import("Framework.Bootstrap", __module) +local Log = __MODULE__.Import("Framework.Log", __module) +function ____exports.OnInit(gameInstance) + Bootstrap.Init(gameInstance) + Log.Info("LuaGameInstance.OnInit()") end -function LuaGameInstance.ReceiveShutdown(self) - Log.Info("LuaGameInstance:ReceiveShutdown()") +function ____exports.OnShutdown(_gameInstance) + Log.Info("LuaGameInstance.OnShutdown()") Bootstrap.Shutdown() end -return LuaGameInstance +function __module.UpdateImports() +end diff --git a/Script/lua/Game/LuaGameMode.lua b/Script/lua/Game/LuaGameMode.lua index 73d1b81..55313d3 100644 --- a/Script/lua/Game/LuaGameMode.lua +++ b/Script/lua/Game/LuaGameMode.lua @@ -1,20 +1,21 @@ -local Log = require("Framework.Log") -local LuaGameMode = UnLua.Class() -function LuaGameMode.ReceiveBeginPlay(self) - Log.Info("LuaGameMode:ReceiveBeginPlay() - Demo scene started") +local ____exports = __module.env +local Log = __MODULE__.Import("Framework.Log", __module) +function ____exports.OnBeginPlay(gameMode) + Log.Info("LuaGameMode.OnBeginPlay() - Demo scene started") UE.UKismetSystemLibrary.PrintString( - self, - "[UnLua Demo] LuaGameMode initialized!", + gameMode, + "[UnLua Demo] LuaGameMode initialized (Pure TS Callback Mode)!", true, true, UE.FLinearColor(0.3, 0.85, 1, 1), 5 ) end -function LuaGameMode.ReceiveEndPlay(self, EndPlayReason) +function ____exports.OnEndPlay(_gameMode, endPlayReason) Log.Info( - "LuaGameMode:ReceiveEndPlay(reason=%s)", - tostring(EndPlayReason) + "LuaGameMode.OnEndPlay(reason=%s)", + tostring(endPlayReason) ) end -return LuaGameMode +function __module.UpdateImports() +end diff --git a/Script/lua/Game/LuaPlayerController.lua b/Script/lua/Game/LuaPlayerController.lua index e0be1e7..57e5094 100644 --- a/Script/lua/Game/LuaPlayerController.lua +++ b/Script/lua/Game/LuaPlayerController.lua @@ -1,22 +1,23 @@ -local Log = require("Framework.Log") -local EventBus = require("Framework.EventBus") -local HotReload = require("Framework.HotReload") -local LuaPlayerController = UnLua.Class() -function LuaPlayerController.ReceiveBeginPlay(self) - Log.Info("LuaPlayerController:ReceiveBeginPlay() - Ready for [Space]=Ping, [R]=HotReload") +local ____exports = __module.env +local Log = __MODULE__.Import("Framework.Log", __module) +local EventBus = __MODULE__.Import("Framework.EventBus", __module) +local HotReload = __MODULE__.Import("Framework.HotReload", __module) +function ____exports.OnBeginPlay(_pc) + Log.Info("LuaPlayerController.OnBeginPlay() - Ready for [Space]=Ping, [R]=HotReload") end -function LuaPlayerController.OnDemoPingPressed(self) - Log.Info("LuaPlayerController:OnDemoPingPressed() -> Emitting Demo.Ping") +function ____exports.OnDemoPingPressed(_pc) + Log.Info("LuaPlayerController.OnDemoPingPressed() -> Emitting Demo.Ping") EventBus.Emit("Demo.Ping", "LuaPlayerController") end -function LuaPlayerController.OnDemoHotReloadPressed(self) - Log.Info("LuaPlayerController:OnDemoHotReloadPressed() -> Triggering HotReload.ReloadAll()") +function ____exports.OnDemoHotReloadPressed(_pc) + Log.Info("LuaPlayerController.OnDemoHotReloadPressed() -> Triggering HotReload.ReloadAll()") HotReload.ReloadAll() end -function LuaPlayerController.ReceiveEndPlay(self, EndPlayReason) +function ____exports.OnEndPlay(_pc, endPlayReason) Log.Info( - "LuaPlayerController:ReceiveEndPlay(reason=%s)", - tostring(EndPlayReason) + "LuaPlayerController.OnEndPlay(reason=%s)", + tostring(endPlayReason) ) end -return LuaPlayerController +function __module.UpdateImports() +end diff --git a/Script/lua/Lib/Class.lua b/Script/lua/Lib/Class.lua new file mode 100644 index 0000000..649840f --- /dev/null +++ b/Script/lua/Lib/Class.lua @@ -0,0 +1,53 @@ +-- 热更友好的纯 TS 类定义运行时(扁平全局函数,零表查询开销,完全兼容 TSTL lualib_bundle) + +local pairs = pairs +local type = type + +local allClassTbl = {} + +local function __TS__DefineClass(name, mod) + local modname = mod and mod.name or "" + local fullName = modname .. ":" .. name + local cls = allClassTbl[fullName] + if cls then + -- 热更重载时清理原型上已删除的旧方法,保持既有实例与子类继承链的原型表引用不变 + local modSys = _G.__MODULE__ + if modSys and modSys.IsReimporting and modSys.IsReimporting(mod) then + local proto = cls.prototype + if proto then + for k, v in pairs(proto) do + if k ~= "__index" and k ~= "constructor" and type(v) == "function" then + proto[k] = nil + end + end + end + end + cls.name = name + return cls + end + + cls = { + __classdefine__ = true, + __fullname__ = fullName, + name = name, + prototype = {}, + } + cls.prototype.__index = cls.prototype + cls.prototype.constructor = cls + + allClassTbl[fullName] = cls + return cls +end + +_G.__TS__DefineClass = __TS__DefineClass + +return { + DefineClass = __TS__DefineClass, + allClassTbl = allClassTbl, + GetClass = function(fullName) + return allClassTbl[fullName] + end, + AllClasses = function() + return allClassTbl + end, +} diff --git a/Script/lua/Lib/Module.lua b/Script/lua/Lib/Module.lua new file mode 100644 index 0000000..13bebd9 --- /dev/null +++ b/Script/lua/Lib/Module.lua @@ -0,0 +1,649 @@ +local __MODULE__ = {} + +__MODULE__.loadedModuleTbl = {} +__MODULE__.loadedPathToModuleTbl = {} +__MODULE__.loadingModuleTbl = {} +__MODULE__.moduleWaitingForLoadingModuleTbl = {} +__MODULE__.loadedModuleNameList = {} +__MODULE__.importingStack = {} +__MODULE__.systemMeta = {} + +local loadedModuleTbl = __MODULE__.loadedModuleTbl +local loadedPathToModuleTbl = __MODULE__.loadedPathToModuleTbl +local loadingModuleTbl = __MODULE__.loadingModuleTbl +local moduleWaitingForLoadingModuleTbl = __MODULE__.moduleWaitingForLoadingModuleTbl +local loadedModuleNameList = __MODULE__.loadedModuleNameList + +local reimportingCount = 0 + +local DEBUG_IMPORT_LOG = false +local DEBUG_IMPORT_STACK = false +local DEBUG_TRACE_MODULE_MEMORY = false +local DEBUG_TRACE_IMPORT_LOOP = false +local DEBUG_WARNING_WAITING_MODULE = false + +local print = print +local pairs = pairs +local ipairs = ipairs +local pcall = pcall +local type = type +local error = error +local assert = assert +local tostring = tostring +local setmetatable = setmetatable +local load = load +local table_insert = table.insert +local table_remove = table.remove +local table_sort = table.sort +local table_concat = table.concat +local string_format = string.format +local string_gsub = string.gsub +local string_sub = string.sub +local string_match = string.match +local string_rep = string.rep +local debug_getupvalue = debug and debug.getupvalue or nil +local debug_setupvalue = debug and debug.setupvalue or nil +local debug_getinfo = debug and debug.getinfo or nil +local debug_traceback = debug and debug.traceback or nil + +local okMd5, md5Mod = pcall(require, "md5") +local md5 = okMd5 and md5Mod or nil + +local ProfileBeginSample = nil +local ProfileEndSample = nil + +local Errorf = function(fmt, ...) + print("ERROR: " .. string_format(fmt, ...)) +end + +local Infof = function(fmt, ...) + print(string_format(fmt, ...)) +end + +local GetTime = function() + return os.time() +end + +local function NormalizeModName(mname) + return (string_gsub(mname, "/", ".")) +end + +local function ModuleNameToPath(modname) + return (string_gsub(NormalizeModName(modname), "%.", "/")) .. ".lua" +end + +local function NormalizeChunkPath(path) + if string_sub(path, 1, 1) == "@" then + return path + end + return "@" .. path +end + +local function OnLoadModuleFileDefault(modname) + local filepath = ModuleNameToPath(modname) + local f = io and io.open and io.open(filepath, "rb") + if f then + local data = f:read("a") + f:close() + local hash = nil + if md5 and md5.sumhexa then + hash = md5.sumhexa(data) + end + return data, filepath, hash + end + return nil, filepath, nil +end + +local OnLoadModuleFile = OnLoadModuleFileDefault +local hasCustomLoadModuleFile = false + +local function LoadModuleChunkFromString(modname, data, chunkname, env) + local chunk, err = load(data, chunkname, nil, env) + if chunk == nil then + error(err) + end + return chunk +end + +local function TryLoadChunkFromSearchers(modname, env) + local searchers = package and (package.searchers or package.loaders) + if type(searchers) ~= "table" then + return nil, nil, nil + end + + for _, searcher in ipairs(searchers) do + if type(searcher) == "function" then + local res, extra = searcher(modname) + if type(res) == "function" then + if debug_getupvalue and debug_setupvalue then + local upName = debug_getupvalue(res, 1) + if upName == "_ENV" then + debug_setupvalue(res, 1, env) + end + end + local chunkname = nil + if type(extra) == "string" and #extra > 0 then + chunkname = NormalizeChunkPath(extra) + elseif debug_getinfo then + local info = debug_getinfo(res, "S") + if info and type(info.source) == "string" and #info.source > 0 then + chunkname = NormalizeChunkPath(info.source) + end + end + if not chunkname then + chunkname = "@" .. ModuleNameToPath(modname) + end + return res, chunkname, nil + end + end + end + + return nil, nil, nil +end + +local function OnLoadModuleChunkDefault(modname, env) + if hasCustomLoadModuleFile then + local data, path, hash = OnLoadModuleFile(modname) + if data == nil then + error("fail to load module: " .. modname) + end + local chunkname = NormalizeChunkPath(path or ModuleNameToPath(modname)) + return LoadModuleChunkFromString(modname, data, chunkname, env), chunkname, hash + end + + local chunk, chunkname, hash = TryLoadChunkFromSearchers(modname, env) + if chunk ~= nil then + return chunk, chunkname, hash + end + + local data, path, fileHash = OnLoadModuleFileDefault(modname) + if data == nil then + error("fail to load module: " .. modname) + end + local fallbackChunkName = NormalizeChunkPath(path or ModuleNameToPath(modname)) + return LoadModuleChunkFromString(modname, data, fallbackChunkName, env), fallbackChunkName, fileHash +end + +local OnLoadModuleChunk = OnLoadModuleChunkDefault + +-- 精确匹配 loader +local exactLoaderTbl = {} +-- pattern -> loader(按 pattern 长度降序排列,最长匹配优先) +local patternLoaderTbl = {} + +local function FindLoader(modname) + local loader = exactLoaderTbl[modname] + if loader then + return loader + end + for _, entry in ipairs(patternLoaderTbl) do + if string_match(modname, entry.pattern) then + return entry.loader + end + end + return nil +end + +local function LoadModuleFile(modname) + return OnLoadModuleFile(modname) +end + +local function LoadModuleChunk(modname, env) + local loader = FindLoader(modname) + if loader then + return loader(modname, env) + end + return OnLoadModuleChunk(modname, env) +end + +__MODULE__.OnLoadModuleFileDefault = OnLoadModuleFileDefault +__MODULE__.OnLoadModuleChunkDefault = OnLoadModuleChunkDefault +__MODULE__.ModuleNameToPath = ModuleNameToPath +__MODULE__.LoadModuleFile = LoadModuleFile +__MODULE__.LoadModuleChunk = LoadModuleChunk +__MODULE__.LoadModuleChunkFromString = LoadModuleChunkFromString + +function __MODULE__.SetOnLoadModuleFile(func) + OnLoadModuleFile = assert(func) + hasCustomLoadModuleFile = true +end + +function __MODULE__.SetOnLoadModuleChunk(func) + OnLoadModuleChunk = assert(func) +end + +local function UpdateExports(M, meta) + if meta.UpdateExports then + meta.UpdateExports(M) + end +end + +local function UpdateImports(M, meta) + if meta.UpdateImports then + meta.UpdateImports(M) + end +end + +local function PushModuleStack(modname) + local ent = { modname = modname } + + if DEBUG_TRACE_MODULE_MEMORY then + collectgarbage("collect") + ent.mem0 = collectgarbage("count") + end + + local maybeLoopPos + if DEBUG_TRACE_IMPORT_LOOP then + for i = #__MODULE__.importingStack, 1, -1 do + if __MODULE__.importingStack[i].modname == modname then + maybeLoopPos = i + break + end + end + end + + table_insert(__MODULE__.importingStack, ent) + + if DEBUG_TRACE_IMPORT_LOOP and maybeLoopPos then + Errorf("!!!! maybe import loopback: %s\n%s", modname, __MODULE__.GetImportingStack(maybeLoopPos)) + end +end + +local function PopModuleStack() + local ent = table_remove(__MODULE__.importingStack) + + if DEBUG_TRACE_MODULE_MEMORY and ent then + local modname = ent.modname + collectgarbage("collect") + local mem1 = collectgarbage("count") + local memDeltaFull = math.max(mem1 - ent.mem0, 0) + local memDelta = math.max(memDeltaFull - (ent.memNoSelf or 0)) + if #__MODULE__.importingStack > 0 then + local parentEnt = __MODULE__.importingStack[#__MODULE__.importingStack] + parentEnt.memNoSelf = (parentEnt.memNoSelf or 0) + memDeltaFull + end + Infof("MODULE_MEMO,%s,%f,%f", modname, mem1, memDelta) + end +end + +local function AddWaitingModule(modname, waitingModule) + if not waitingModule then + return + end + local arr = moduleWaitingForLoadingModuleTbl[modname] + if arr == nil then + arr = {} + moduleWaitingForLoadingModuleTbl[modname] = arr + end + arr[#arr + 1] = waitingModule +end + +local function ReloadWaitingModule(modname) + local arrModuleWaiting = moduleWaitingForLoadingModuleTbl[modname] + if arrModuleWaiting then + moduleWaitingForLoadingModuleTbl[modname] = nil + if DEBUG_WARNING_WAITING_MODULE and #arrModuleWaiting > 10 then + print(string_format("!!! too many waiting module for: %s, waiting count: %d", modname, #arrModuleWaiting)) + end + for _, waitingMeta in ipairs(arrModuleWaiting) do + local updateImports = waitingMeta.UpdateImports + if updateImports then + updateImports(waitingMeta.env) + end + end + end +end + +local function DoInitialImport(modname, loadModuleChunk) + local bt + if DEBUG_IMPORT_LOG then + bt = GetTime() + Infof("{{{ Import: %s", modname) + end + + if ProfileBeginSample then + ProfileBeginSample(modname) + end + + if DEBUG_IMPORT_STACK then + PushModuleStack(modname) + end + + local M = {} + setmetatable(M, { __index = _G, __name = "Module<" .. modname .. ">" }) + + local meta = { + name = modname, + env = M, + imports = {}, + __data__ = {}, + reimporting = false, + hasReexports = false, + } + setmetatable(meta, { __name = "ModuleMeta<" .. modname .. ">" }) + M.__module = meta + + if loadModuleChunk == nil then + loadModuleChunk = LoadModuleChunk + end + + loadingModuleTbl[modname] = M + + local ok, err = pcall(function() + local chunk, path, hash = loadModuleChunk(modname, M) + if chunk == nil or path == nil then + error(string_format("cannot found module file at: %s for module [%s]", tostring(path), modname)) + end + + meta.modulefunc = chunk + meta.filepath = path + meta.hash = hash + meta.__data__ = {} + + chunk() + + loadingModuleTbl[modname] = nil + loadedModuleTbl[modname] = M + loadedPathToModuleTbl[path] = M + + UpdateImports(M, meta) + UpdateExports(M, meta) + + if meta.StashData then + meta.StashData(M, meta.__data__) + end + + if meta.OnImport then + meta.OnImport() + end + + UpdateExports(M, meta) + + -- 刷新因循环依赖而等待本模块加载完成的模块 + ReloadWaitingModule(modname) + + table_insert(loadedModuleNameList, modname) + + if __MODULE__.OnModuleLoaded then + __MODULE__.OnModuleLoaded(modname) + end + end) + + if not ok then + loadingModuleTbl[modname] = nil + moduleWaitingForLoadingModuleTbl[modname] = nil + if loadedModuleTbl[modname] == nil and meta.filepath then + loadedPathToModuleTbl[meta.filepath] = nil + end + end + + if DEBUG_IMPORT_STACK then + PopModuleStack() + end + + if ProfileEndSample then + ProfileEndSample() + end + + if DEBUG_IMPORT_LOG then + local dt = GetTime() - bt + Infof("}}} Import: %s, dt=%f", modname, dt) + end + + if not ok then + error(err, 0) + end + + return M +end + +function __MODULE__.Import(amodname, callerModule, loadModuleChunk) + local modname = NormalizeModName(amodname) + local M = loadedModuleTbl[modname] + + if M == nil then + M = loadingModuleTbl[modname] + if M ~= nil then + AddWaitingModule(modname, callerModule) + end + end + + if M == nil then + M = DoInitialImport(modname, loadModuleChunk) + end + + if callerModule and callerModule.imports then + callerModule.imports[modname] = true + end + + return M +end + +function __MODULE__.GetModuleByName(modname) + return loadedModuleTbl[NormalizeModName(modname)] +end + +function __MODULE__.GetModuleByPath(path) + return loadedPathToModuleTbl[path] +end + +function __MODULE__.GetAllModulePaths() + return loadedPathToModuleTbl +end + +function __MODULE__.AllLoadedModules() + return loadedModuleTbl +end + +local function UpdateDependsLocalImport(modname, visited) + visited = visited or {} + if visited[modname] then + return + end + visited[modname] = true + + local downstreams = {} + for iname, M in pairs(loadedModuleTbl) do + if M.__module.imports[modname] then + downstreams[iname] = M + end + end + + for iname, M in pairs(downstreams) do + local dmeta = M.__module + if dmeta.UpdateImports then + dmeta.UpdateImports(M) + end + if dmeta.OnDepModuleReimported then + dmeta.OnDepModuleReimported(modname) + end + if dmeta.hasReexports then + UpdateDependsLocalImport(iname, visited) + end + end +end + +local function ReimportModule(M, loadModuleChunk) + local meta = M.__module + local modname = meta.name + + if loadModuleChunk == nil then + loadModuleChunk = LoadModuleChunk + end + + local chunk, pathOrErr, hash = loadModuleChunk(modname, M) + if chunk == nil then + local tb = debug_traceback and debug_traceback() or "" + Errorf("%s, %s", tostring(pathOrErr), tb) + return nil, pathOrErr + end + + meta.__data__ = {} + if meta.StashData then + meta.StashData(M, meta.__data__) + end + + local oldImports = meta.imports + local oldHasReexports = meta.hasReexports + meta.imports = {} + meta.hasReexports = false + + if not M.__shared__ then + for k in pairs(M) do + if k ~= "__module" then + M[k] = nil + end + end + end + + local okChunk, chunkErr = pcall(chunk) + if not okChunk then + meta.imports = oldImports + meta.hasReexports = oldHasReexports + error(chunkErr, 0) + end + + meta.modulefunc = chunk + meta.hash = hash + if type(pathOrErr) == "string" and #pathOrErr > 0 then + if meta.filepath and meta.filepath ~= pathOrErr and loadedPathToModuleTbl[meta.filepath] == M then + loadedPathToModuleTbl[meta.filepath] = nil + end + meta.filepath = pathOrErr + loadedPathToModuleTbl[pathOrErr] = M + end + + if meta.RestoreData then + meta.RestoreData(M, meta.__data__) + end + + UpdateImports(M, meta) + UpdateExports(M, meta) + + UpdateDependsLocalImport(modname) + + if meta.OnReimport then + meta.OnReimport() + end + + return M +end + +function __MODULE__.IsReimporting(meta) + if meta then + return meta.reimporting == true + end + return reimportingCount > 0 +end + +function __MODULE__.Reimport(target, loadModuleChunk) + Infof("reimport %s", target) + local M + if string_sub(target, 1, 1) == "@" then + M = loadedPathToModuleTbl[target] + else + M = loadedModuleTbl[NormalizeModName(target)] + end + if M == nil then + local err = string_format("no module loaded: %s", target) + Errorf("%s", err) + return nil, err + end + + local meta = M.__module + local previousReimporting = meta.reimporting + meta.reimporting = true + reimportingCount = reimportingCount + 1 + local ok, result, err = pcall(ReimportModule, M, loadModuleChunk) + reimportingCount = reimportingCount - 1 + meta.reimporting = previousReimporting + if not ok then + error(result, 0) + end + return result, err +end + +function __MODULE__.ReimportSafely(target, loadModuleChunk) + local ok, result, err = pcall(__MODULE__.Reimport, target, loadModuleChunk) + if not ok then + return false, result + end + if result == nil then + return false, err + end + return true, nil +end + +--[[ + RegistryModuleLoader 注册模块加载器 + modpattern: 精确模块名 (如 "Config.Items") 或以 ^ 开头的 Lua pattern (如 "^Config%.") + loader: function(modname, env) -> (chunk, chunkname, hash) +]] +function __MODULE__.RegistryModuleLoader(modpattern, loader) + if string_sub(modpattern, 1, 1) == "^" then + local updated = false + for _, entry in ipairs(patternLoaderTbl) do + if entry.pattern == modpattern then + entry.loader = loader + updated = true + break + end + end + if not updated then + table_insert(patternLoaderTbl, { pattern = modpattern, loader = loader }) + table_sort(patternLoaderTbl, function(a, b) + return #a.pattern > #b.pattern + end) + end + else + exactLoaderTbl[NormalizeModName(modpattern)] = loader + end +end + +function __MODULE__.Config(args) + if args.Errorf then + Errorf = args.Errorf + end + if args.Infof then + Infof = args.Infof + end +end + +function __MODULE__.SetSystemMeta(key, value) + __MODULE__.systemMeta[key] = value +end + +function __MODULE__.GetSystemMeta(key) + return __MODULE__.systemMeta[key] +end + +function __MODULE__.SetProfile(args) + if args.GetTime then + GetTime = args.GetTime + end + if args.ProfileBeginSample then + ProfileBeginSample = args.ProfileBeginSample + end + if args.ProfileEndSample then + ProfileEndSample = args.ProfileEndSample + end +end + +function __MODULE__.GetImportingStack(maybeLoopPos) + local level = 0 + local indent = " " + local T = {} + for i, ent in ipairs(__MODULE__.importingStack) do + local line = string_rep(indent, level) .. ent.modname + if maybeLoopPos and maybeLoopPos == i then + line = line .. " <====" + end + table_insert(T, line) + level = level + 1 + end + return table_concat(T, "\n") +end + +_G.__MODULE__ = __MODULE__ + +return __MODULE__ diff --git a/Script/lua/Tests/Extra/HotReloadAndFrameworkTest.lua b/Script/lua/Tests/Extra/HotReloadAndFrameworkTest.lua index d51229c..688f76b 100644 --- a/Script/lua/Tests/Extra/HotReloadAndFrameworkTest.lua +++ b/Script/lua/Tests/Extra/HotReloadAndFrameworkTest.lua @@ -1,20 +1,20 @@ -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local Suite = ____TestRunner.Suite -local Test = ____TestRunner.Test -local AssertEqual = ____TestRunner.AssertEqual -local AssertTrue = ____TestRunner.AssertTrue -local AssertFalse = ____TestRunner.AssertFalse -local AssertNotNil = ____TestRunner.AssertNotNil -local AssertNil = ____TestRunner.AssertNil -local AssertArrayEqual = ____TestRunner.AssertArrayEqual -local ____MockUnLuaRuntime = require("Tests.Harness.MockUnLuaRuntime") -local CreateBoundInstance = ____MockUnLuaRuntime.CreateBoundInstance -local ResetMockState = ____MockUnLuaRuntime.ResetMockState -local Bootstrap = require("Framework.Bootstrap") -local EventBus = require("Framework.EventBus") -local HotReload = require("Framework.HotReload") -local LuaDemoActor = require("Game.LuaDemoActor") +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local Suite = M__Tests_Harness_TestRunner.Suite +local Test = M__Tests_Harness_TestRunner.Test +local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual +local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue +local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse +local AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil +local AssertNil = M__Tests_Harness_TestRunner.AssertNil +local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual +local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) +local CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance +local ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState +local Bootstrap = __MODULE__.Import("Framework.Bootstrap", __module) +local EventBus = __MODULE__.Import("Framework.EventBus", __module) +local HotReload = __MODULE__.Import("Framework.HotReload", __module) +local LuaDemoActor = __MODULE__.Import("Game.LuaDemoActor", __module) function ____exports.RunHotReloadAndFrameworkTests() Suite( "Extra.FrameworkAndHotReload", @@ -105,7 +105,7 @@ function ____exports.RunHotReloadAndFrameworkTests() end ) Test( - "LuaDemoActor full integration: BeginPlay, Tick, Ping color cycle, HotReload event & EndPlay cleanup", + "LuaDemoActor full integration: pure TS callback BeginPlay, Tick, Ping color cycle, HotReload & EndPlay cleanup", function() ResetMockState() EventBus.Clear() @@ -113,8 +113,8 @@ function ____exports.RunHotReloadAndFrameworkTests() local colorApplyCount = 0 local rotationAddCount = 0 local lastVerticalOffset = 0 - local demoActor = CreateBoundInstance( - LuaDemoActor, + local fakeActor = CreateBoundInstance( + {}, "ALuaDemoActor", { SpinSpeed = 90, @@ -134,24 +134,37 @@ function ____exports.RunHotReloadAndFrameworkTests() end } ) - demoActor:ReceiveBeginPlay() + LuaDemoActor.OnBeginPlay(fakeActor) AssertEqual(colorApplyCount, 1) AssertTrue((string.find(lastStatusText, "Pings: 0", 1, true)) ~= nil) - demoActor:ReceiveTick(0.25) + AssertTrue((string.find(lastStatusText, "Speed: 60", 1, true)) ~= nil) + LuaDemoActor.OnTick(fakeActor, 0.25) AssertEqual(rotationAddCount, 1) AssertTrue(lastVerticalOffset ~= 0) EventBus.Emit("Demo.Ping", "TestSuite") AssertEqual(colorApplyCount, 2) AssertTrue((string.find(lastStatusText, "Pings: 1", 1, true)) ~= nil) EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, "Game.LuaDemoActor") + AssertEqual(colorApplyCount, 3) AssertTrue((string.find(lastStatusText, "Reloads: 1", 1, true)) ~= nil) - demoActor:ReceiveEndPlay(UE.EEndPlayReason.Destroyed) + LuaDemoActor.OnEndPlay(fakeActor, UE.EEndPlayReason.Destroyed) EventBus.Emit("Demo.Ping", "AfterEndPlay") - AssertEqual(colorApplyCount, 2) + AssertEqual(colorApplyCount, 3) EventBus.Clear() end ) end ) end -return ____exports +function __module.UpdateImports() + Suite = M__Tests_Harness_TestRunner.Suite + Test = M__Tests_Harness_TestRunner.Test + AssertEqual = M__Tests_Harness_TestRunner.AssertEqual + AssertTrue = M__Tests_Harness_TestRunner.AssertTrue + AssertFalse = M__Tests_Harness_TestRunner.AssertFalse + AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil + AssertNil = M__Tests_Harness_TestRunner.AssertNil + AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual + CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance + ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState +end diff --git a/Script/lua/Tests/Extra/LifecycleAndMemoryTest.lua b/Script/lua/Tests/Extra/LifecycleAndMemoryTest.lua index 32f4ed6..f8ac861 100644 --- a/Script/lua/Tests/Extra/LifecycleAndMemoryTest.lua +++ b/Script/lua/Tests/Extra/LifecycleAndMemoryTest.lua @@ -1,18 +1,18 @@ -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local Suite = ____TestRunner.Suite -local Test = ____TestRunner.Test -local AssertEqual = ____TestRunner.AssertEqual -local AssertTrue = ____TestRunner.AssertTrue -local AssertFalse = ____TestRunner.AssertFalse -local AssertNil = ____TestRunner.AssertNil -local AssertArrayEqual = ____TestRunner.AssertArrayEqual -local ____MockUnLuaRuntime = require("Tests.Harness.MockUnLuaRuntime") -local AdvanceMockTime = ____MockUnLuaRuntime.AdvanceMockTime -local CreateBoundInstance = ____MockUnLuaRuntime.CreateBoundInstance -local GetMockState = ____MockUnLuaRuntime.GetMockState -local ResetMockState = ____MockUnLuaRuntime.ResetMockState -local EventBus = require("Framework.EventBus") +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local Suite = M__Tests_Harness_TestRunner.Suite +local Test = M__Tests_Harness_TestRunner.Test +local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual +local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue +local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse +local AssertNil = M__Tests_Harness_TestRunner.AssertNil +local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual +local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) +local AdvanceMockTime = M__Tests_Harness_MockUnLuaRuntime.AdvanceMockTime +local CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance +local GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState +local ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState +local EventBus = __MODULE__.Import("Framework.EventBus", __module) local LifecycleSafetyActor = require("Tests.Extra.LifecycleSafetyActor") function ____exports.RunLifecycleAndMemoryTests() Suite( @@ -89,4 +89,16 @@ function ____exports.RunLifecycleAndMemoryTests() end ) end -return ____exports +function __module.UpdateImports() + Suite = M__Tests_Harness_TestRunner.Suite + Test = M__Tests_Harness_TestRunner.Test + AssertEqual = M__Tests_Harness_TestRunner.AssertEqual + AssertTrue = M__Tests_Harness_TestRunner.AssertTrue + AssertFalse = M__Tests_Harness_TestRunner.AssertFalse + AssertNil = M__Tests_Harness_TestRunner.AssertNil + AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual + AdvanceMockTime = M__Tests_Harness_MockUnLuaRuntime.AdvanceMockTime + CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance + GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState + ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState +end diff --git a/Script/lua/Tests/Extra/LifecycleSafetyActor.lua b/Script/lua/Tests/Extra/LifecycleSafetyActor.lua index 579d0e5..53d66cf 100644 --- a/Script/lua/Tests/Extra/LifecycleSafetyActor.lua +++ b/Script/lua/Tests/Extra/LifecycleSafetyActor.lua @@ -1,4 +1,4 @@ -local EventBus = require("Framework.EventBus") +local EventBus = __MODULE__.Import("Framework.EventBus") local LifecycleSafetyActor = UnLua.Class() function LifecycleSafetyActor.ReceiveBeginPlay(self) self.Overridden.ReceiveBeginPlay(self) diff --git a/Script/lua/Tests/Extra/Lua54PitfallsTest.lua b/Script/lua/Tests/Extra/Lua54PitfallsTest.lua index 78f2010..72aaa8d 100644 --- a/Script/lua/Tests/Extra/Lua54PitfallsTest.lua +++ b/Script/lua/Tests/Extra/Lua54PitfallsTest.lua @@ -1,11 +1,11 @@ -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local Suite = ____TestRunner.Suite -local Test = ____TestRunner.Test -local AssertEqual = ____TestRunner.AssertEqual -local AssertTrue = ____TestRunner.AssertTrue -local AssertNear = ____TestRunner.AssertNear -local AssertArrayEqual = ____TestRunner.AssertArrayEqual +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local Suite = M__Tests_Harness_TestRunner.Suite +local Test = M__Tests_Harness_TestRunner.Test +local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual +local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue +local AssertNear = M__Tests_Harness_TestRunner.AssertNear +local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual local function EscapeLuaPattern(literal) local escaped = string.gsub(literal, "([%(%)%.%%%+%-%*%?%[%]%^%$])", "%%%1") return escaped @@ -168,4 +168,11 @@ function ____exports.RunLua54PitfallsTests() end ) end -return ____exports +function __module.UpdateImports() + Suite = M__Tests_Harness_TestRunner.Suite + Test = M__Tests_Harness_TestRunner.Test + AssertEqual = M__Tests_Harness_TestRunner.AssertEqual + AssertTrue = M__Tests_Harness_TestRunner.AssertTrue + AssertNear = M__Tests_Harness_TestRunner.AssertNear + AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual +end diff --git a/Script/lua/Tests/Gameplay/BehaviorTree.lua b/Script/lua/Tests/Gameplay/BehaviorTree.lua index a768314..ac48134 100644 --- a/Script/lua/Tests/Gameplay/BehaviorTree.lua +++ b/Script/lua/Tests/Gameplay/BehaviorTree.lua @@ -1,7 +1,5 @@ -local ____lualib = require("lualib_bundle") -local __TS__Class = ____lualib.__TS__Class -local ____exports = {} -____exports.BTCondition = __TS__Class() +local ____exports = __module.env +____exports.BTCondition = __TS__DefineClass("BTCondition", __module) local BTCondition = ____exports.BTCondition BTCondition.name = "BTCondition" function BTCondition.prototype.____constructor(self, check) @@ -12,7 +10,7 @@ function BTCondition.prototype.Tick(self, ctx) end function BTCondition.prototype.Reset(self) end -____exports.BTAction = __TS__Class() +____exports.BTAction = __TS__DefineClass("BTAction", __module) local BTAction = ____exports.BTAction BTAction.name = "BTAction" function BTAction.prototype.____constructor(self, action) @@ -23,7 +21,7 @@ function BTAction.prototype.Tick(self, ctx) end function BTAction.prototype.Reset(self) end -____exports.BTSequence = __TS__Class() +____exports.BTSequence = __TS__DefineClass("BTSequence", __module) local BTSequence = ____exports.BTSequence BTSequence.name = "BTSequence" function BTSequence.prototype.____constructor(self, children) @@ -55,7 +53,7 @@ function BTSequence.prototype.Reset(self) end end end -____exports.BTSelector = __TS__Class() +____exports.BTSelector = __TS__DefineClass("BTSelector", __module) local BTSelector = ____exports.BTSelector BTSelector.name = "BTSelector" function BTSelector.prototype.____constructor(self, children) @@ -87,7 +85,7 @@ function BTSelector.prototype.Reset(self) end end end -____exports.BTInverter = __TS__Class() +____exports.BTInverter = __TS__DefineClass("BTInverter", __module) local BTInverter = ____exports.BTInverter BTInverter.name = "BTInverter" function BTInverter.prototype.____constructor(self, child) @@ -106,7 +104,7 @@ end function BTInverter.prototype.Reset(self) self.child:Reset() end -____exports.BTCooldown = __TS__Class() +____exports.BTCooldown = __TS__DefineClass("BTCooldown", __module) local BTCooldown = ____exports.BTCooldown BTCooldown.name = "BTCooldown" function BTCooldown.prototype.____constructor(self, child, cooldownSeconds) @@ -127,4 +125,5 @@ end function BTCooldown.prototype.Reset(self) self.child:Reset() end -return ____exports +function __module.UpdateImports() +end diff --git a/Script/lua/Tests/Gameplay/BuffAndAttributeSystem.lua b/Script/lua/Tests/Gameplay/BuffAndAttributeSystem.lua index fbaf64d..72895ea 100644 --- a/Script/lua/Tests/Gameplay/BuffAndAttributeSystem.lua +++ b/Script/lua/Tests/Gameplay/BuffAndAttributeSystem.lua @@ -1,7 +1,5 @@ -local ____lualib = require("lualib_bundle") -local __TS__Class = ____lualib.__TS__Class -local ____exports = {} -____exports.AttributeAndBuffComponent = __TS__Class() +local ____exports = __module.env +____exports.AttributeAndBuffComponent = __TS__DefineClass("AttributeAndBuffComponent", __module) local AttributeAndBuffComponent = ____exports.AttributeAndBuffComponent AttributeAndBuffComponent.name = "AttributeAndBuffComponent" function AttributeAndBuffComponent.prototype.____constructor(self, initialStats) @@ -177,4 +175,5 @@ function AttributeAndBuffComponent.prototype.Notify(self, attr, val) end end end -return ____exports +function __module.UpdateImports() +end diff --git a/Script/lua/Tests/Gameplay/CoroutineTaskRunner.lua b/Script/lua/Tests/Gameplay/CoroutineTaskRunner.lua index da065d5..fdfdc08 100644 --- a/Script/lua/Tests/Gameplay/CoroutineTaskRunner.lua +++ b/Script/lua/Tests/Gameplay/CoroutineTaskRunner.lua @@ -1,7 +1,5 @@ -local ____lualib = require("lualib_bundle") -local __TS__Class = ____lualib.__TS__Class -local ____exports = {} -____exports.CoroutineTaskRunner = __TS__Class() +local ____exports = __module.env +____exports.CoroutineTaskRunner = __TS__DefineClass("CoroutineTaskRunner", __module) local CoroutineTaskRunner = ____exports.CoroutineTaskRunner CoroutineTaskRunner.name = "CoroutineTaskRunner" function CoroutineTaskRunner.prototype.____constructor(self) @@ -125,4 +123,5 @@ function CoroutineTaskRunner.WaitUntil(predicate) local cmd = {kind = "wait_until", predicate = predicate} coroutine.yield(cmd) end -return ____exports +function __module.UpdateImports() +end diff --git a/Script/lua/Tests/Gameplay/FSM.lua b/Script/lua/Tests/Gameplay/FSM.lua index 00b969f..cb71aa7 100644 --- a/Script/lua/Tests/Gameplay/FSM.lua +++ b/Script/lua/Tests/Gameplay/FSM.lua @@ -1,7 +1,5 @@ -local ____lualib = require("lualib_bundle") -local __TS__Class = ____lualib.__TS__Class -local ____exports = {} -____exports.StateMachine = __TS__Class() +local ____exports = __module.env +____exports.StateMachine = __TS__DefineClass("StateMachine", __module) local StateMachine = ____exports.StateMachine StateMachine.name = "StateMachine" function StateMachine.prototype.____constructor(self, ctx) @@ -85,4 +83,5 @@ end function StateMachine.prototype.GetHistory(self) return self.history end -return ____exports +function __module.UpdateImports() +end diff --git a/Script/lua/Tests/Gameplay/GameplaySuite.lua b/Script/lua/Tests/Gameplay/GameplaySuite.lua index c07aa5d..db27b64 100644 --- a/Script/lua/Tests/Gameplay/GameplaySuite.lua +++ b/Script/lua/Tests/Gameplay/GameplaySuite.lua @@ -1,37 +1,37 @@ local ____lualib = require("lualib_bundle") local __TS__New = ____lualib.__TS__New -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local Suite = ____TestRunner.Suite -local Test = ____TestRunner.Test -local AssertEqual = ____TestRunner.AssertEqual -local AssertNear = ____TestRunner.AssertNear -local AssertTrue = ____TestRunner.AssertTrue -local AssertFalse = ____TestRunner.AssertFalse -local AssertNil = ____TestRunner.AssertNil -local AssertArrayEqual = ____TestRunner.AssertArrayEqual -local ____MockUnLuaRuntime = require("Tests.Harness.MockUnLuaRuntime") -local CreateBoundInstance = ____MockUnLuaRuntime.CreateBoundInstance -local ____FSM = require("Tests.Gameplay.FSM") -local StateMachine = ____FSM.StateMachine -local ____ObjectPool = require("Tests.Gameplay.ObjectPool") -local ObjectPool = ____ObjectPool.ObjectPool -local ____TimerScheduler = require("Tests.Gameplay.TimerScheduler") -local TimerScheduler = ____TimerScheduler.TimerScheduler -local CooldownTracker = ____TimerScheduler.CooldownTracker -local ____BuffAndAttributeSystem = require("Tests.Gameplay.BuffAndAttributeSystem") -local AttributeAndBuffComponent = ____BuffAndAttributeSystem.AttributeAndBuffComponent -local ____InventorySystem = require("Tests.Gameplay.InventorySystem") -local InventorySystem = ____InventorySystem.InventorySystem -local ____CoroutineTaskRunner = require("Tests.Gameplay.CoroutineTaskRunner") -local CoroutineTaskRunner = ____CoroutineTaskRunner.CoroutineTaskRunner -local ____BehaviorTree = require("Tests.Gameplay.BehaviorTree") -local BTAction = ____BehaviorTree.BTAction -local BTCondition = ____BehaviorTree.BTCondition -local BTCooldown = ____BehaviorTree.BTCooldown -local BTInverter = ____BehaviorTree.BTInverter -local BTSelector = ____BehaviorTree.BTSelector -local BTSequence = ____BehaviorTree.BTSequence +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local Suite = M__Tests_Harness_TestRunner.Suite +local Test = M__Tests_Harness_TestRunner.Test +local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual +local AssertNear = M__Tests_Harness_TestRunner.AssertNear +local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue +local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse +local AssertNil = M__Tests_Harness_TestRunner.AssertNil +local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual +local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) +local CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance +local M__Tests_Gameplay_FSM = __MODULE__.Import("Tests.Gameplay.FSM", __module) +local StateMachine = M__Tests_Gameplay_FSM.StateMachine +local M__Tests_Gameplay_ObjectPool = __MODULE__.Import("Tests.Gameplay.ObjectPool", __module) +local ObjectPool = M__Tests_Gameplay_ObjectPool.ObjectPool +local M__Tests_Gameplay_TimerScheduler = __MODULE__.Import("Tests.Gameplay.TimerScheduler", __module) +local TimerScheduler = M__Tests_Gameplay_TimerScheduler.TimerScheduler +local CooldownTracker = M__Tests_Gameplay_TimerScheduler.CooldownTracker +local M__Tests_Gameplay_BuffAndAttributeSystem = __MODULE__.Import("Tests.Gameplay.BuffAndAttributeSystem", __module) +local AttributeAndBuffComponent = M__Tests_Gameplay_BuffAndAttributeSystem.AttributeAndBuffComponent +local M__Tests_Gameplay_InventorySystem = __MODULE__.Import("Tests.Gameplay.InventorySystem", __module) +local InventorySystem = M__Tests_Gameplay_InventorySystem.InventorySystem +local M__Tests_Gameplay_CoroutineTaskRunner = __MODULE__.Import("Tests.Gameplay.CoroutineTaskRunner", __module) +local CoroutineTaskRunner = M__Tests_Gameplay_CoroutineTaskRunner.CoroutineTaskRunner +local M__Tests_Gameplay_BehaviorTree = __MODULE__.Import("Tests.Gameplay.BehaviorTree", __module) +local BTAction = M__Tests_Gameplay_BehaviorTree.BTAction +local BTCondition = M__Tests_Gameplay_BehaviorTree.BTCondition +local BTCooldown = M__Tests_Gameplay_BehaviorTree.BTCooldown +local BTInverter = M__Tests_Gameplay_BehaviorTree.BTInverter +local BTSelector = M__Tests_Gameplay_BehaviorTree.BTSelector +local BTSequence = M__Tests_Gameplay_BehaviorTree.BTSequence function ____exports.RunGameplayTests() Suite( "Gameplay.Systems", @@ -489,4 +489,27 @@ function ____exports.RunGameplayTests() end ) end -return ____exports +function __module.UpdateImports() + Suite = M__Tests_Harness_TestRunner.Suite + Test = M__Tests_Harness_TestRunner.Test + AssertEqual = M__Tests_Harness_TestRunner.AssertEqual + AssertNear = M__Tests_Harness_TestRunner.AssertNear + AssertTrue = M__Tests_Harness_TestRunner.AssertTrue + AssertFalse = M__Tests_Harness_TestRunner.AssertFalse + AssertNil = M__Tests_Harness_TestRunner.AssertNil + AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual + CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance + StateMachine = M__Tests_Gameplay_FSM.StateMachine + ObjectPool = M__Tests_Gameplay_ObjectPool.ObjectPool + TimerScheduler = M__Tests_Gameplay_TimerScheduler.TimerScheduler + CooldownTracker = M__Tests_Gameplay_TimerScheduler.CooldownTracker + AttributeAndBuffComponent = M__Tests_Gameplay_BuffAndAttributeSystem.AttributeAndBuffComponent + InventorySystem = M__Tests_Gameplay_InventorySystem.InventorySystem + CoroutineTaskRunner = M__Tests_Gameplay_CoroutineTaskRunner.CoroutineTaskRunner + BTAction = M__Tests_Gameplay_BehaviorTree.BTAction + BTCondition = M__Tests_Gameplay_BehaviorTree.BTCondition + BTCooldown = M__Tests_Gameplay_BehaviorTree.BTCooldown + BTInverter = M__Tests_Gameplay_BehaviorTree.BTInverter + BTSelector = M__Tests_Gameplay_BehaviorTree.BTSelector + BTSequence = M__Tests_Gameplay_BehaviorTree.BTSequence +end diff --git a/Script/lua/Tests/Gameplay/InventorySystem.lua b/Script/lua/Tests/Gameplay/InventorySystem.lua index a5d59fd..4b0d60c 100644 --- a/Script/lua/Tests/Gameplay/InventorySystem.lua +++ b/Script/lua/Tests/Gameplay/InventorySystem.lua @@ -1,7 +1,5 @@ -local ____lualib = require("lualib_bundle") -local __TS__Class = ____lualib.__TS__Class -local ____exports = {} -____exports.InventorySystem = __TS__Class() +local ____exports = __module.env +____exports.InventorySystem = __TS__DefineClass("InventorySystem", __module) local InventorySystem = ____exports.InventorySystem InventorySystem.name = "InventorySystem" function InventorySystem.prototype.____constructor(self, capacity) @@ -158,4 +156,5 @@ function InventorySystem.prototype.Deserialize(self, data) self.slots[idx] = {itemId = s.itemId, count = s.count} end end -return ____exports +function __module.UpdateImports() +end diff --git a/Script/lua/Tests/Gameplay/ObjectPool.lua b/Script/lua/Tests/Gameplay/ObjectPool.lua index 9686177..a445b5f 100644 --- a/Script/lua/Tests/Gameplay/ObjectPool.lua +++ b/Script/lua/Tests/Gameplay/ObjectPool.lua @@ -1,7 +1,5 @@ -local ____lualib = require("lualib_bundle") -local __TS__Class = ____lualib.__TS__Class -local ____exports = {} -____exports.ObjectPool = __TS__Class() +local ____exports = __module.env +____exports.ObjectPool = __TS__DefineClass("ObjectPool", __module) local ObjectPool = ____exports.ObjectPool ObjectPool.name = "ObjectPool" function ObjectPool.prototype.____constructor(self, options) @@ -58,4 +56,5 @@ end function ObjectPool.prototype.GetTotalCreated(self) return self.totalCreated end -return ____exports +function __module.UpdateImports() +end diff --git a/Script/lua/Tests/Gameplay/TimerScheduler.lua b/Script/lua/Tests/Gameplay/TimerScheduler.lua index 47c013f..494f5d6 100644 --- a/Script/lua/Tests/Gameplay/TimerScheduler.lua +++ b/Script/lua/Tests/Gameplay/TimerScheduler.lua @@ -1,7 +1,5 @@ -local ____lualib = require("lualib_bundle") -local __TS__Class = ____lualib.__TS__Class -local ____exports = {} -____exports.TimerScheduler = __TS__Class() +local ____exports = __module.env +____exports.TimerScheduler = __TS__DefineClass("TimerScheduler", __module) local TimerScheduler = ____exports.TimerScheduler TimerScheduler.name = "TimerScheduler" function TimerScheduler.prototype.____constructor(self) @@ -123,7 +121,7 @@ function TimerScheduler.prototype.GetActiveCount(self) end return count end -____exports.CooldownTracker = __TS__Class() +____exports.CooldownTracker = __TS__DefineClass("CooldownTracker", __module) local CooldownTracker = ____exports.CooldownTracker CooldownTracker.name = "CooldownTracker" function CooldownTracker.prototype.____constructor(self) @@ -156,4 +154,5 @@ function CooldownTracker.prototype.Tick(self, dt) end end end -return ____exports +function __module.UpdateImports() +end diff --git a/Script/lua/Tests/Harness/MockUnLuaRuntime.lua b/Script/lua/Tests/Harness/MockUnLuaRuntime.lua index 1980a46..a976618 100644 --- a/Script/lua/Tests/Harness/MockUnLuaRuntime.lua +++ b/Script/lua/Tests/Harness/MockUnLuaRuntime.lua @@ -1,4 +1,4 @@ -local ____exports = {} +local ____exports = __module.env local state function ____exports.GetMockState() return state @@ -1078,4 +1078,5 @@ function ____exports.InstallIfNeeded() } } end -return ____exports +function __module.UpdateImports() +end diff --git a/Script/lua/Tests/Harness/TestRunner.lua b/Script/lua/Tests/Harness/TestRunner.lua index 93607f4..2a3b860 100644 --- a/Script/lua/Tests/Harness/TestRunner.lua +++ b/Script/lua/Tests/Harness/TestRunner.lua @@ -1,4 +1,4 @@ -local ____exports = {} +local ____exports = __module.env local currentSuite = "Default" local results = {} function ____exports.Reset() @@ -159,4 +159,5 @@ function ____exports.PrintReport() print(____exports.FormatReport(summary)) return summary end -return ____exports +function __module.UpdateImports() +end diff --git a/Script/lua/Tests/RunAllTests.lua b/Script/lua/Tests/RunAllTests.lua index 3479f01..6e2b1e8 100644 --- a/Script/lua/Tests/RunAllTests.lua +++ b/Script/lua/Tests/RunAllTests.lua @@ -1,27 +1,27 @@ -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local Reset = ____TestRunner.Reset -local PrintReport = ____TestRunner.PrintReport -local ____MockUnLuaRuntime = require("Tests.Harness.MockUnLuaRuntime") -local InstallIfNeeded = ____MockUnLuaRuntime.InstallIfNeeded -local ____BasicTypesAndControlFlow = require("Tests.Syntax.BasicTypesAndControlFlow") -local RunBasicTypesAndControlFlowTests = ____BasicTypesAndControlFlow.RunBasicTypesAndControlFlowTests -local ____FunctionsClosuresAndTuples = require("Tests.Syntax.FunctionsClosuresAndTuples") -local RunFunctionsClosuresAndTuplesTests = ____FunctionsClosuresAndTuples.RunFunctionsClosuresAndTuplesTests -local ____PureClassesAndGenerics = require("Tests.Syntax.PureClassesAndGenerics") -local RunPureClassesAndGenericsTests = ____PureClassesAndGenerics.RunPureClassesAndGenericsTests -local ____UnLuaSyntaxSuite = require("Tests.Syntax.UnLuaSyntaxSuite") -local RunUnLuaSyntaxTests = ____UnLuaSyntaxSuite.RunUnLuaSyntaxTests -local ____UnLuaExamplesSuite = require("Tests.UnLuaExamples.UnLuaExamplesSuite") -local RunUnLuaExamplesTests = ____UnLuaExamplesSuite.RunUnLuaExamplesTests -local ____GameplaySuite = require("Tests.Gameplay.GameplaySuite") -local RunGameplayTests = ____GameplaySuite.RunGameplayTests -local ____HotReloadAndFrameworkTest = require("Tests.Extra.HotReloadAndFrameworkTest") -local RunHotReloadAndFrameworkTests = ____HotReloadAndFrameworkTest.RunHotReloadAndFrameworkTests -local ____Lua54PitfallsTest = require("Tests.Extra.Lua54PitfallsTest") -local RunLua54PitfallsTests = ____Lua54PitfallsTest.RunLua54PitfallsTests -local ____LifecycleAndMemoryTest = require("Tests.Extra.LifecycleAndMemoryTest") -local RunLifecycleAndMemoryTests = ____LifecycleAndMemoryTest.RunLifecycleAndMemoryTests +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local Reset = M__Tests_Harness_TestRunner.Reset +local PrintReport = M__Tests_Harness_TestRunner.PrintReport +local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) +local InstallIfNeeded = M__Tests_Harness_MockUnLuaRuntime.InstallIfNeeded +local M__Tests_Syntax_BasicTypesAndControlFlow = __MODULE__.Import("Tests.Syntax.BasicTypesAndControlFlow", __module) +local RunBasicTypesAndControlFlowTests = M__Tests_Syntax_BasicTypesAndControlFlow.RunBasicTypesAndControlFlowTests +local M__Tests_Syntax_FunctionsClosuresAndTuples = __MODULE__.Import("Tests.Syntax.FunctionsClosuresAndTuples", __module) +local RunFunctionsClosuresAndTuplesTests = M__Tests_Syntax_FunctionsClosuresAndTuples.RunFunctionsClosuresAndTuplesTests +local M__Tests_Syntax_PureClassesAndGenerics = __MODULE__.Import("Tests.Syntax.PureClassesAndGenerics", __module) +local RunPureClassesAndGenericsTests = M__Tests_Syntax_PureClassesAndGenerics.RunPureClassesAndGenericsTests +local M__Tests_Syntax_UnLuaSyntaxSuite = __MODULE__.Import("Tests.Syntax.UnLuaSyntaxSuite", __module) +local RunUnLuaSyntaxTests = M__Tests_Syntax_UnLuaSyntaxSuite.RunUnLuaSyntaxTests +local M__Tests_UnLuaExamples_UnLuaExamplesSuite = __MODULE__.Import("Tests.UnLuaExamples.UnLuaExamplesSuite", __module) +local RunUnLuaExamplesTests = M__Tests_UnLuaExamples_UnLuaExamplesSuite.RunUnLuaExamplesTests +local M__Tests_Gameplay_GameplaySuite = __MODULE__.Import("Tests.Gameplay.GameplaySuite", __module) +local RunGameplayTests = M__Tests_Gameplay_GameplaySuite.RunGameplayTests +local M__Tests_Extra_HotReloadAndFrameworkTest = __MODULE__.Import("Tests.Extra.HotReloadAndFrameworkTest", __module) +local RunHotReloadAndFrameworkTests = M__Tests_Extra_HotReloadAndFrameworkTest.RunHotReloadAndFrameworkTests +local M__Tests_Extra_Lua54PitfallsTest = __MODULE__.Import("Tests.Extra.Lua54PitfallsTest", __module) +local RunLua54PitfallsTests = M__Tests_Extra_Lua54PitfallsTest.RunLua54PitfallsTests +local M__Tests_Extra_LifecycleAndMemoryTest = __MODULE__.Import("Tests.Extra.LifecycleAndMemoryTest", __module) +local RunLifecycleAndMemoryTests = M__Tests_Extra_LifecycleAndMemoryTest.RunLifecycleAndMemoryTests function ____exports.RunAll() InstallIfNeeded() Reset() @@ -43,4 +43,17 @@ if g.__TS2LUA_TEST_AUTO_RUN__ == true then os.exit(1) end end -return ____exports +function __module.UpdateImports() + Reset = M__Tests_Harness_TestRunner.Reset + PrintReport = M__Tests_Harness_TestRunner.PrintReport + InstallIfNeeded = M__Tests_Harness_MockUnLuaRuntime.InstallIfNeeded + RunBasicTypesAndControlFlowTests = M__Tests_Syntax_BasicTypesAndControlFlow.RunBasicTypesAndControlFlowTests + RunFunctionsClosuresAndTuplesTests = M__Tests_Syntax_FunctionsClosuresAndTuples.RunFunctionsClosuresAndTuplesTests + RunPureClassesAndGenericsTests = M__Tests_Syntax_PureClassesAndGenerics.RunPureClassesAndGenericsTests + RunUnLuaSyntaxTests = M__Tests_Syntax_UnLuaSyntaxSuite.RunUnLuaSyntaxTests + RunUnLuaExamplesTests = M__Tests_UnLuaExamples_UnLuaExamplesSuite.RunUnLuaExamplesTests + RunGameplayTests = M__Tests_Gameplay_GameplaySuite.RunGameplayTests + RunHotReloadAndFrameworkTests = M__Tests_Extra_HotReloadAndFrameworkTest.RunHotReloadAndFrameworkTests + RunLua54PitfallsTests = M__Tests_Extra_Lua54PitfallsTest.RunLua54PitfallsTests + RunLifecycleAndMemoryTests = M__Tests_Extra_LifecycleAndMemoryTest.RunLifecycleAndMemoryTests +end diff --git a/Script/lua/Tests/Syntax/BasicTypesAndControlFlow.lua b/Script/lua/Tests/Syntax/BasicTypesAndControlFlow.lua index 6f8f6da..5c84076 100644 --- a/Script/lua/Tests/Syntax/BasicTypesAndControlFlow.lua +++ b/Script/lua/Tests/Syntax/BasicTypesAndControlFlow.lua @@ -2,16 +2,16 @@ local ____lualib = require("lualib_bundle") local __TS__SparseArrayNew = ____lualib.__TS__SparseArrayNew local __TS__SparseArrayPush = ____lualib.__TS__SparseArrayPush local __TS__SparseArraySpread = ____lualib.__TS__SparseArraySpread -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local Suite = ____TestRunner.Suite -local Test = ____TestRunner.Test -local AssertEqual = ____TestRunner.AssertEqual -local AssertNear = ____TestRunner.AssertNear -local AssertTrue = ____TestRunner.AssertTrue -local AssertFalse = ____TestRunner.AssertFalse -local AssertNil = ____TestRunner.AssertNil -local AssertArrayEqual = ____TestRunner.AssertArrayEqual +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local Suite = M__Tests_Harness_TestRunner.Suite +local Test = M__Tests_Harness_TestRunner.Test +local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual +local AssertNear = M__Tests_Harness_TestRunner.AssertNear +local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue +local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse +local AssertNil = M__Tests_Harness_TestRunner.AssertNil +local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual local function EvaluateCommand(action) repeat local ____switch3 = action.kind @@ -246,4 +246,13 @@ function ____exports.RunBasicTypesAndControlFlowTests() end ) end -return ____exports +function __module.UpdateImports() + Suite = M__Tests_Harness_TestRunner.Suite + Test = M__Tests_Harness_TestRunner.Test + AssertEqual = M__Tests_Harness_TestRunner.AssertEqual + AssertNear = M__Tests_Harness_TestRunner.AssertNear + AssertTrue = M__Tests_Harness_TestRunner.AssertTrue + AssertFalse = M__Tests_Harness_TestRunner.AssertFalse + AssertNil = M__Tests_Harness_TestRunner.AssertNil + AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual +end diff --git a/Script/lua/Tests/Syntax/FunctionsClosuresAndTuples.lua b/Script/lua/Tests/Syntax/FunctionsClosuresAndTuples.lua index 50abcb8..e3e092d 100644 --- a/Script/lua/Tests/Syntax/FunctionsClosuresAndTuples.lua +++ b/Script/lua/Tests/Syntax/FunctionsClosuresAndTuples.lua @@ -2,15 +2,15 @@ local ____lualib = require("lualib_bundle") local __TS__ArraySplice = ____lualib.__TS__ArraySplice local __TS__ArraySort = ____lualib.__TS__ArraySort local __TS__ArrayIndexOf = ____lualib.__TS__ArrayIndexOf -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local Suite = ____TestRunner.Suite -local Test = ____TestRunner.Test -local AssertEqual = ____TestRunner.AssertEqual -local AssertTrue = ____TestRunner.AssertTrue -local AssertFalse = ____TestRunner.AssertFalse -local AssertNil = ____TestRunner.AssertNil -local AssertArrayEqual = ____TestRunner.AssertArrayEqual +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local Suite = M__Tests_Harness_TestRunner.Suite +local Test = M__Tests_Harness_TestRunner.Test +local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual +local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue +local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse +local AssertNil = M__Tests_Harness_TestRunner.AssertNil +local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual local function DivideWithRemainder(a, b) if b == 0 then return false, 0, 0 @@ -191,4 +191,12 @@ function ____exports.RunFunctionsClosuresAndTuplesTests() end ) end -return ____exports +function __module.UpdateImports() + Suite = M__Tests_Harness_TestRunner.Suite + Test = M__Tests_Harness_TestRunner.Test + AssertEqual = M__Tests_Harness_TestRunner.AssertEqual + AssertTrue = M__Tests_Harness_TestRunner.AssertTrue + AssertFalse = M__Tests_Harness_TestRunner.AssertFalse + AssertNil = M__Tests_Harness_TestRunner.AssertNil + AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual +end diff --git a/Script/lua/Tests/Syntax/PureClassesAndGenerics.lua b/Script/lua/Tests/Syntax/PureClassesAndGenerics.lua index 2a00822..e7f3289 100644 --- a/Script/lua/Tests/Syntax/PureClassesAndGenerics.lua +++ b/Script/lua/Tests/Syntax/PureClassesAndGenerics.lua @@ -1,17 +1,16 @@ local ____lualib = require("lualib_bundle") -local __TS__Class = ____lualib.__TS__Class local __TS__ClassExtends = ____lualib.__TS__ClassExtends local __TS__New = ____lualib.__TS__New local __TS__InstanceOf = ____lualib.__TS__InstanceOf -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local Suite = ____TestRunner.Suite -local Test = ____TestRunner.Test -local AssertEqual = ____TestRunner.AssertEqual -local AssertTrue = ____TestRunner.AssertTrue -local AssertFalse = ____TestRunner.AssertFalse -local AssertNil = ____TestRunner.AssertNil -local BaseEntity = __TS__Class() +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local Suite = M__Tests_Harness_TestRunner.Suite +local Test = M__Tests_Harness_TestRunner.Test +local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual +local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue +local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse +local AssertNil = M__Tests_Harness_TestRunner.AssertNil +local BaseEntity = __TS__DefineClass("BaseEntity", __module) BaseEntity.name = "BaseEntity" function BaseEntity.prototype.____constructor(self, id, name) self.id = id @@ -23,7 +22,7 @@ end function BaseEntity.prototype.GetName(self) return self.name end -local PureMonster = __TS__Class() +local PureMonster = __TS__DefineClass("PureMonster", __module) PureMonster.name = "PureMonster" __TS__ClassExtends(PureMonster, BaseEntity) function PureMonster.prototype.____constructor(self, id, name, level) @@ -43,7 +42,7 @@ function PureMonster.CompareLevel(a, b) return a:GetLevel() - b:GetLevel() end PureMonster.DefaultLevel = 1 -local RingBuffer = __TS__Class() +local RingBuffer = __TS__DefineClass("RingBuffer", __module) RingBuffer.name = "RingBuffer" function RingBuffer.prototype.____constructor(self, capacity) self.buffer = {} @@ -190,4 +189,11 @@ function ____exports.RunPureClassesAndGenericsTests() end ) end -return ____exports +function __module.UpdateImports() + Suite = M__Tests_Harness_TestRunner.Suite + Test = M__Tests_Harness_TestRunner.Test + AssertEqual = M__Tests_Harness_TestRunner.AssertEqual + AssertTrue = M__Tests_Harness_TestRunner.AssertTrue + AssertFalse = M__Tests_Harness_TestRunner.AssertFalse + AssertNil = M__Tests_Harness_TestRunner.AssertNil +end diff --git a/Script/lua/Tests/Syntax/UnLuaSyntaxSuite.lua b/Script/lua/Tests/Syntax/UnLuaSyntaxSuite.lua index 2f31003..63d4048 100644 --- a/Script/lua/Tests/Syntax/UnLuaSyntaxSuite.lua +++ b/Script/lua/Tests/Syntax/UnLuaSyntaxSuite.lua @@ -1,14 +1,14 @@ -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local Suite = ____TestRunner.Suite -local Test = ____TestRunner.Test -local AssertEqual = ____TestRunner.AssertEqual -local AssertTrue = ____TestRunner.AssertTrue -local AssertArrayEqual = ____TestRunner.AssertArrayEqual -local ____MockUnLuaRuntime = require("Tests.Harness.MockUnLuaRuntime") -local CreateBoundInstance = ____MockUnLuaRuntime.CreateBoundInstance -local GetMockState = ____MockUnLuaRuntime.GetMockState -local ResetMockState = ____MockUnLuaRuntime.ResetMockState +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local Suite = M__Tests_Harness_TestRunner.Suite +local Test = M__Tests_Harness_TestRunner.Test +local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual +local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue +local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual +local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) +local CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance +local GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState +local ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState local UnLuaBaseActor = require("Tests.Syntax.UnLuaBaseActor") local UnLuaGrandChildActor = require("Tests.Syntax.UnLuaGrandChildActor") local UnLuaExplicitWidget = require("Tests.Syntax.UnLuaExplicitWidget") @@ -120,4 +120,13 @@ function ____exports.RunUnLuaSyntaxTests() end ) end -return ____exports +function __module.UpdateImports() + Suite = M__Tests_Harness_TestRunner.Suite + Test = M__Tests_Harness_TestRunner.Test + AssertEqual = M__Tests_Harness_TestRunner.AssertEqual + AssertTrue = M__Tests_Harness_TestRunner.AssertTrue + AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual + CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance + GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState + ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState +end diff --git a/Script/lua/Tests/UE/UERuntimeSuite.lua b/Script/lua/Tests/UE/UERuntimeSuite.lua index 28f08df..149cdeb 100644 --- a/Script/lua/Tests/UE/UERuntimeSuite.lua +++ b/Script/lua/Tests/UE/UERuntimeSuite.lua @@ -1,32 +1,32 @@ -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local Reset = ____TestRunner.Reset -local PrintReport = ____TestRunner.PrintReport -local Suite = ____TestRunner.Suite -local Test = ____TestRunner.Test -local AssertEqual = ____TestRunner.AssertEqual -local AssertNear = ____TestRunner.AssertNear -local AssertTrue = ____TestRunner.AssertTrue -local AssertFalse = ____TestRunner.AssertFalse -local AssertNotNil = ____TestRunner.AssertNotNil -local AssertNil = ____TestRunner.AssertNil -local AssertArrayEqual = ____TestRunner.AssertArrayEqual -local ____BasicTypesAndControlFlow = require("Tests.Syntax.BasicTypesAndControlFlow") -local RunBasicTypesAndControlFlowTests = ____BasicTypesAndControlFlow.RunBasicTypesAndControlFlowTests -local ____FunctionsClosuresAndTuples = require("Tests.Syntax.FunctionsClosuresAndTuples") -local RunFunctionsClosuresAndTuplesTests = ____FunctionsClosuresAndTuples.RunFunctionsClosuresAndTuplesTests -local ____PureClassesAndGenerics = require("Tests.Syntax.PureClassesAndGenerics") -local RunPureClassesAndGenericsTests = ____PureClassesAndGenerics.RunPureClassesAndGenericsTests -local ____GameplaySuite = require("Tests.Gameplay.GameplaySuite") -local RunGameplayTests = ____GameplaySuite.RunGameplayTests -local ____Lua54PitfallsTest = require("Tests.Extra.Lua54PitfallsTest") -local RunLua54PitfallsTests = ____Lua54PitfallsTest.RunLua54PitfallsTests -local EventBus = require("Framework.EventBus") -local HotReload = require("Framework.HotReload") -local ____Ex06_NativeContainers = require("Tests.UnLuaExamples.Ex06_NativeContainers") -local VerifyTArrayOperations = ____Ex06_NativeContainers.VerifyTArrayOperations -local VerifyTMapOperations = ____Ex06_NativeContainers.VerifyTMapOperations -local VerifyTSetOperations = ____Ex06_NativeContainers.VerifyTSetOperations +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local Reset = M__Tests_Harness_TestRunner.Reset +local PrintReport = M__Tests_Harness_TestRunner.PrintReport +local Suite = M__Tests_Harness_TestRunner.Suite +local Test = M__Tests_Harness_TestRunner.Test +local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual +local AssertNear = M__Tests_Harness_TestRunner.AssertNear +local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue +local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse +local AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil +local AssertNil = M__Tests_Harness_TestRunner.AssertNil +local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual +local M__Tests_Syntax_BasicTypesAndControlFlow = __MODULE__.Import("Tests.Syntax.BasicTypesAndControlFlow", __module) +local RunBasicTypesAndControlFlowTests = M__Tests_Syntax_BasicTypesAndControlFlow.RunBasicTypesAndControlFlowTests +local M__Tests_Syntax_FunctionsClosuresAndTuples = __MODULE__.Import("Tests.Syntax.FunctionsClosuresAndTuples", __module) +local RunFunctionsClosuresAndTuplesTests = M__Tests_Syntax_FunctionsClosuresAndTuples.RunFunctionsClosuresAndTuplesTests +local M__Tests_Syntax_PureClassesAndGenerics = __MODULE__.Import("Tests.Syntax.PureClassesAndGenerics", __module) +local RunPureClassesAndGenericsTests = M__Tests_Syntax_PureClassesAndGenerics.RunPureClassesAndGenericsTests +local M__Tests_Gameplay_GameplaySuite = __MODULE__.Import("Tests.Gameplay.GameplaySuite", __module) +local RunGameplayTests = M__Tests_Gameplay_GameplaySuite.RunGameplayTests +local M__Tests_Extra_Lua54PitfallsTest = __MODULE__.Import("Tests.Extra.Lua54PitfallsTest", __module) +local RunLua54PitfallsTests = M__Tests_Extra_Lua54PitfallsTest.RunLua54PitfallsTests +local EventBus = __MODULE__.Import("Framework.EventBus", __module) +local HotReload = __MODULE__.Import("Framework.HotReload", __module) +local M__Tests_UnLuaExamples_Ex06_NativeContainers = __MODULE__.Import("Tests.UnLuaExamples.Ex06_NativeContainers", __module) +local VerifyTArrayOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTArrayOperations +local VerifyTMapOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTMapOperations +local VerifyTSetOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTSetOperations local UnLuaBaseActorClass = require("Tests.Syntax.UnLuaBaseActor") local function TickUEWorld(steps, deltaSeconds) local tickFn = _G.__UE_TEST_TICK @@ -325,7 +325,7 @@ function ____exports.RunUERuntimeSuite(world) end ) Test( - "Real UE ALuaDemoActor (IUnLuaInterface static binding) + EventBus + Tick + EndPlay", + "Real UE ALuaDemoActor (C++ callback -> pure TS Game.LuaDemoActor) + EventBus + Tick + EndPlay", function() local demoActor = world:SpawnActor( UE.ALuaDemoActor.StaticClass(), @@ -339,7 +339,7 @@ function ____exports.RunUERuntimeSuite(world) AssertNotNil(demoActor) AssertTrue(demoActor:IsA(UE.ALuaDemoActor.StaticClass())) local initText = demoActor:GetStatusTextString() - AssertTrue((string.find(initText, "UnLua Active", 1, true)) ~= nil) + AssertTrue((string.find(initText, "Pure-TS Actor", 1, true)) ~= nil, "initText: " .. initText) AssertTrue((string.find(initText, "Pings: 0", 1, true)) ~= nil) if canTickWorld then TickUEWorld(5, 0.05) @@ -443,6 +443,72 @@ function ____exports.RunUERuntimeSuite(world) AssertTrue(ok) end ) + Test( + "Real UE single-file __MODULE__.Reimport hot-reloads Game.LuaDemoActor spin speed and color live", + function() + local demoActor = world:SpawnActor( + UE.ALuaDemoActor.StaticClass(), + UE.FTransform( + UE.FRotator(0, 0, 0):ToQuat(), + UE.FVector(0, 0, 200), + UE.FVector(1, 1, 1) + ), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn + ) + AssertNotNil(demoActor) + local beforeText = demoActor:GetStatusTextString() + AssertTrue((string.find(beforeText, "v1", 1, true)) ~= nil) + AssertTrue((string.find(beforeText, "Speed: 60", 1, true)) ~= nil) + AssertTrue((string.find(beforeText, "Color: Cyan", 1, true)) ~= nil) + local actorMod = __MODULE__.Import("Game.LuaDemoActor") + local activeBefore = actorMod:GetActiveControllerCount() + AssertTrue(activeBefore >= 1) + local defaultDir = UE.ULuaHotUpdateSubsystem.GetDefaultScriptDir() + local overrideDir = UE.ULuaHotUpdateSubsystem.GetHotUpdateScriptDir() + local srcPath = defaultDir .. "/Game/LuaDemoActor.lua" + local dstGameDir = overrideDir .. "/Game" + local dstPath = dstGameDir .. "/LuaDemoActor.lua" + local srcFile = (io.open(srcPath, "rb")) + AssertNotNil(srcFile) + local origLua = srcFile:read("a") + srcFile:close() + local patchedLua = string.gsub(origLua, "\"v1\"", "\"v2-HOTFIX\"") + patchedLua = string.gsub(patchedLua, "ACTOR_SPIN_SPEED = 60", "ACTOR_SPIN_SPEED = 240") + patchedLua = string.gsub(patchedLua, "\"Cyan\"", "\"Crimson\"") + patchedLua = string.gsub(patchedLua, "R = 0%.08", "R = 0.95") + patchedLua = string.gsub(patchedLua, "G = 0%.78", "G = 0.12") + patchedLua = string.gsub(patchedLua, "B = 0%.95", "B = 0.18") + os.execute(string.format("mkdir -p \"%s\"", dstGameDir)) + local dstFile = (io.open(dstPath, "wb")) + AssertNotNil(dstFile) + dstFile:write(patchedLua) + dstFile:close() + local okReload, errReload = HotReload.ReloadModule("Game.LuaDemoActor") + os.remove(dstPath) + AssertTrue( + okReload, + tostring(errReload) + ) + AssertEqual(actorMod.DEMO_VERSION, "v2-HOTFIX") + AssertEqual(actorMod.ACTOR_SPIN_SPEED, 240) + AssertEqual( + actorMod:GetActiveControllerCount(), + activeBefore + ) + local newColor = demoActor:GetCubeColor() + AssertNear(newColor.R, 0.95, 0.01) + AssertNear(newColor.G, 0.12, 0.01) + local afterText = demoActor:GetStatusTextString() + AssertTrue((string.find(afterText, "v2-HOTFIX", 1, true)) ~= nil, "afterText: " .. afterText) + AssertTrue((string.find(afterText, "Speed: 240", 1, true)) ~= nil, "afterText: " .. afterText) + AssertTrue((string.find(afterText, "Color: Crimson", 1, true)) ~= nil, "afterText: " .. afterText) + local okRestore = HotReload.ReloadModule("Game.LuaDemoActor") + AssertTrue(okRestore) + AssertEqual(actorMod.DEMO_VERSION, "v1") + AssertEqual(actorMod.ACTOR_SPIN_SPEED, 60) + demoActor:K2_DestroyActor() + end + ) end ) end @@ -461,4 +527,24 @@ function ____exports.RunAllInUE(world) end return PrintReport() end -return ____exports +function __module.UpdateImports() + Reset = M__Tests_Harness_TestRunner.Reset + PrintReport = M__Tests_Harness_TestRunner.PrintReport + Suite = M__Tests_Harness_TestRunner.Suite + Test = M__Tests_Harness_TestRunner.Test + AssertEqual = M__Tests_Harness_TestRunner.AssertEqual + AssertNear = M__Tests_Harness_TestRunner.AssertNear + AssertTrue = M__Tests_Harness_TestRunner.AssertTrue + AssertFalse = M__Tests_Harness_TestRunner.AssertFalse + AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil + AssertNil = M__Tests_Harness_TestRunner.AssertNil + AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual + RunBasicTypesAndControlFlowTests = M__Tests_Syntax_BasicTypesAndControlFlow.RunBasicTypesAndControlFlowTests + RunFunctionsClosuresAndTuplesTests = M__Tests_Syntax_FunctionsClosuresAndTuples.RunFunctionsClosuresAndTuplesTests + RunPureClassesAndGenericsTests = M__Tests_Syntax_PureClassesAndGenerics.RunPureClassesAndGenericsTests + RunGameplayTests = M__Tests_Gameplay_GameplaySuite.RunGameplayTests + RunLua54PitfallsTests = M__Tests_Extra_Lua54PitfallsTest.RunLua54PitfallsTests + VerifyTArrayOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTArrayOperations + VerifyTMapOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTMapOperations + VerifyTSetOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTSetOperations +end diff --git a/Script/lua/Tests/UnLuaExamples/Ex06_NativeContainers.lua b/Script/lua/Tests/UnLuaExamples/Ex06_NativeContainers.lua index 057c8d2..1e18f65 100644 --- a/Script/lua/Tests/UnLuaExamples/Ex06_NativeContainers.lua +++ b/Script/lua/Tests/UnLuaExamples/Ex06_NativeContainers.lua @@ -1,10 +1,10 @@ -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local AssertEqual = ____TestRunner.AssertEqual -local AssertTrue = ____TestRunner.AssertTrue -local AssertFalse = ____TestRunner.AssertFalse -local AssertNil = ____TestRunner.AssertNil -local AssertArrayEqual = ____TestRunner.AssertArrayEqual +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual +local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue +local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse +local AssertNil = M__Tests_Harness_TestRunner.AssertNil +local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual --- 参考 UnLua 官方示例 06_NativeContainers: -- 演示 UE.TArray / UE.TMap / UE.TSet 的构造(使用 UE.int32 / UE.FString Token)、 -- 1-based 索引访问、CRUD、ToTable 与原生 pairs() 遍历。 @@ -198,4 +198,10 @@ function ____exports.VerifyTSetOperations() 0 ) end -return ____exports +function __module.UpdateImports() + AssertEqual = M__Tests_Harness_TestRunner.AssertEqual + AssertTrue = M__Tests_Harness_TestRunner.AssertTrue + AssertFalse = M__Tests_Harness_TestRunner.AssertFalse + AssertNil = M__Tests_Harness_TestRunner.AssertNil + AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual +end diff --git a/Script/lua/Tests/UnLuaExamples/UnLuaExamplesSuite.lua b/Script/lua/Tests/UnLuaExamples/UnLuaExamplesSuite.lua index 057b8dc..116c4a7 100644 --- a/Script/lua/Tests/UnLuaExamples/UnLuaExamplesSuite.lua +++ b/Script/lua/Tests/UnLuaExamples/UnLuaExamplesSuite.lua @@ -1,24 +1,24 @@ -local ____exports = {} -local ____TestRunner = require("Tests.Harness.TestRunner") -local Suite = ____TestRunner.Suite -local Test = ____TestRunner.Test -local AssertEqual = ____TestRunner.AssertEqual -local AssertNear = ____TestRunner.AssertNear -local AssertTrue = ____TestRunner.AssertTrue -local AssertFalse = ____TestRunner.AssertFalse -local AssertNotNil = ____TestRunner.AssertNotNil -local AssertArrayEqual = ____TestRunner.AssertArrayEqual -local ____MockUnLuaRuntime = require("Tests.Harness.MockUnLuaRuntime") -local AdvanceMockTime = ____MockUnLuaRuntime.AdvanceMockTime -local CreateBoundInstance = ____MockUnLuaRuntime.CreateBoundInstance -local CreateMockMulticastDelegate = ____MockUnLuaRuntime.CreateMockMulticastDelegate -local CreateMockScriptDelegate = ____MockUnLuaRuntime.CreateMockScriptDelegate -local GetMockState = ____MockUnLuaRuntime.GetMockState -local ResetMockState = ____MockUnLuaRuntime.ResetMockState -local ____Ex06_NativeContainers = require("Tests.UnLuaExamples.Ex06_NativeContainers") -local VerifyTArrayOperations = ____Ex06_NativeContainers.VerifyTArrayOperations -local VerifyTMapOperations = ____Ex06_NativeContainers.VerifyTMapOperations -local VerifyTSetOperations = ____Ex06_NativeContainers.VerifyTSetOperations +local ____exports = __module.env +local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) +local Suite = M__Tests_Harness_TestRunner.Suite +local Test = M__Tests_Harness_TestRunner.Test +local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual +local AssertNear = M__Tests_Harness_TestRunner.AssertNear +local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue +local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse +local AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil +local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual +local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) +local AdvanceMockTime = M__Tests_Harness_MockUnLuaRuntime.AdvanceMockTime +local CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance +local CreateMockMulticastDelegate = M__Tests_Harness_MockUnLuaRuntime.CreateMockMulticastDelegate +local CreateMockScriptDelegate = M__Tests_Harness_MockUnLuaRuntime.CreateMockScriptDelegate +local GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState +local ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState +local M__Tests_UnLuaExamples_Ex06_NativeContainers = __MODULE__.Import("Tests.UnLuaExamples.Ex06_NativeContainers", __module) +local VerifyTArrayOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTArrayOperations +local VerifyTMapOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTMapOperations +local VerifyTSetOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTSetOperations local Ex01_HelloWorld = require("Tests.UnLuaExamples.Ex01_HelloWorld") local Ex02_OverrideBlueprintEvents = require("Tests.UnLuaExamples.Ex02_OverrideBlueprintEvents") local Ex03_BindDelegates = require("Tests.UnLuaExamples.Ex03_BindDelegates") @@ -312,4 +312,22 @@ function ____exports.RunUnLuaExamplesTests() end ) end -return ____exports +function __module.UpdateImports() + Suite = M__Tests_Harness_TestRunner.Suite + Test = M__Tests_Harness_TestRunner.Test + AssertEqual = M__Tests_Harness_TestRunner.AssertEqual + AssertNear = M__Tests_Harness_TestRunner.AssertNear + AssertTrue = M__Tests_Harness_TestRunner.AssertTrue + AssertFalse = M__Tests_Harness_TestRunner.AssertFalse + AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil + AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual + AdvanceMockTime = M__Tests_Harness_MockUnLuaRuntime.AdvanceMockTime + CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance + CreateMockMulticastDelegate = M__Tests_Harness_MockUnLuaRuntime.CreateMockMulticastDelegate + CreateMockScriptDelegate = M__Tests_Harness_MockUnLuaRuntime.CreateMockScriptDelegate + GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState + ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState + VerifyTArrayOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTArrayOperations + VerifyTMapOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTMapOperations + VerifyTSetOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTSetOperations +end diff --git a/Script/lua/lualib_bundle.lua b/Script/lua/lualib_bundle.lua index afb0ba7..1dc0075 100644 --- a/Script/lua/lualib_bundle.lua +++ b/Script/lua/lualib_bundle.lua @@ -1,3 +1,9 @@ +local function __TS__New(target, ...) + local instance = setmetatable({}, target.prototype) + instance:____constructor(...) + return instance +end + local function __TS__CountVarargs(...) return select("#", ...) end @@ -134,13 +140,6 @@ local function __TS__ArrayIndexOf(self, searchElement, fromIndex) return -1 end -local function __TS__Class(self) - local c = {prototype = {}} - c.prototype.__index = c.prototype - c.prototype.constructor = c - return c -end - local function __TS__ClassExtends(target, base) target.____super = base local staticMetatable = setmetatable({__index = base}, base) @@ -166,12 +165,6 @@ local function __TS__ClassExtends(target, base) end end -local function __TS__New(target, ...) - local instance = setmetatable({}, target.prototype) - instance:____constructor(...) - return instance -end - local __TS__Symbol, Symbol do local symbolMetatable = {__tostring = function(self) @@ -210,14 +203,13 @@ local function __TS__InstanceOf(obj, classTbl) end return { + __TS__New = __TS__New, __TS__SparseArrayNew = __TS__SparseArrayNew, __TS__SparseArrayPush = __TS__SparseArrayPush, __TS__SparseArraySpread = __TS__SparseArraySpread, __TS__ArraySplice = __TS__ArraySplice, __TS__ArraySort = __TS__ArraySort, __TS__ArrayIndexOf = __TS__ArrayIndexOf, - __TS__Class = __TS__Class, __TS__ClassExtends = __TS__ClassExtends, - __TS__New = __TS__New, __TS__InstanceOf = __TS__InstanceOf } diff --git a/Script/ts/package-lock.json b/Script/ts/package-lock.json index 8afc2f0..bb53aa8 100644 --- a/Script/ts/package-lock.json +++ b/Script/ts/package-lock.json @@ -8,7 +8,7 @@ "name": "unreal-lua-demo-ts", "version": "1.0.0", "devDependencies": { - "ts2lua-unreal": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#v0.2.2" + "ts2lua-unreal": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#v0.3.0" } }, "node_modules/@typescript-to-lua/language-extensions": { @@ -175,8 +175,8 @@ } }, "node_modules/ts2lua-unreal": { - "version": "0.2.2", - "resolved": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#cb1539d7383e72b32d0fae600199257a05f4d416", + "version": "0.3.0", + "resolved": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#b1a53d8660061dc51dabe5fc5ea0038d8d25a343", "dev": true, "dependencies": { "lua-types": "^2.14.1", diff --git a/Script/ts/package.json b/Script/ts/package.json index 4e665f1..fb1a185 100644 --- a/Script/ts/package.json +++ b/Script/ts/package.json @@ -11,6 +11,6 @@ "info": "ts2lua-unreal info" }, "devDependencies": { - "ts2lua-unreal": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#v0.2.2" + "ts2lua-unreal": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#v0.3.0" } } diff --git a/Script/ts/scripts/run-tests.mjs b/Script/ts/scripts/run-tests.mjs index 124bead..bf1bfba 100644 --- a/Script/ts/scripts/run-tests.mjs +++ b/Script/ts/scripts/run-tests.mjs @@ -25,9 +25,11 @@ const luaPath = [ const code = ` package.path = ${JSON.stringify(luaPath)} .. ";" .. package.path -require("Tests.Harness.MockUnLuaRuntime").InstallIfNeeded() +require("Lib.Module") +require("Lib.Class") +__MODULE__.Import("Tests.Harness.MockUnLuaRuntime").InstallIfNeeded() _G.__TS2LUA_TEST_AUTO_RUN__ = true -require("Tests.RunAllTests") +__MODULE__.Import("Tests.RunAllTests") `; const result = spawnSync(luaBin, ["-e", code], { diff --git a/Script/ts/src/Framework/Bootstrap.ts b/Script/ts/src/Framework/Bootstrap.ts index daa9f86..22a614d 100644 --- a/Script/ts/src/Framework/Bootstrap.ts +++ b/Script/ts/src/Framework/Bootstrap.ts @@ -4,8 +4,12 @@ import * as Log from "./Log"; import * as EventBus from "./EventBus"; import * as HotReload from "./HotReload"; -export const Version = "0.1.0"; +export const Version = "0.2.0"; + +/** @module_data */ export let IsInitialized = false; + +/** @module_data */ export let GameInstance: UE.ULuaGameInstance | undefined = undefined; export function Init(gameInstance: UE.ULuaGameInstance): void { diff --git a/Script/ts/src/Framework/EventBus.ts b/Script/ts/src/Framework/EventBus.ts index 67249c7..b9a33b5 100644 --- a/Script/ts/src/Framework/EventBus.ts +++ b/Script/ts/src/Framework/EventBus.ts @@ -7,6 +7,7 @@ interface EventEntry { owner?: unknown; } +/** @module_data */ let Listeners: Record = {}; export function On( diff --git a/Script/ts/src/Framework/HotReload.ts b/Script/ts/src/Framework/HotReload.ts index 1f50fd1..12d1632 100644 --- a/Script/ts/src/Framework/HotReload.ts +++ b/Script/ts/src/Framework/HotReload.ts @@ -6,14 +6,18 @@ import * as EventBus from "./EventBus"; export const EVENT_BEFORE_RELOAD = "Framework.BeforeHotReload"; export const EVENT_AFTER_RELOAD = "Framework.AfterHotReload"; -function GetLuaPackage(): LuaPackageTable { - return (_G as unknown as Record)["package"] as LuaPackageTable; -} - -function CollectReloadableGameModules(): string[] { +function CollectLoadedHotReloadModules(): string[] { const modules: string[] = []; - for (const [name] of pairs(GetLuaPackage().loaded)) { - if (type(name) === "string" && string.match(name as string, "^Game%.")[0] !== undefined) { + if (__MODULE__ === undefined) { + return modules; + } + for (const [name] of pairs(__MODULE__.AllLoadedModules())) { + if ( + type(name) === "string" && + name !== "Framework.HotReload" && + (string.match(name as string, "^Game%.")[0] !== undefined || + string.match(name as string, "^Framework%.")[0] !== undefined) + ) { modules[modules.length] = name as string; } } @@ -22,74 +26,55 @@ function CollectReloadableGameModules(): string[] { } /** - * Reloads a specific Lua module using UnLua's hot-reload sandbox (falls back to package.loaded reset). + * 单文件热更指定模块(完全基于 Lib/Module.lua 的 __MODULE__.ReimportSafely,零入侵 UnLua)。 */ export function ReloadModule(moduleName: string): LuaMultiReturn<[boolean, unknown?]> { if (type(moduleName) !== "string" || moduleName === "") { return $multi(false, "Invalid module name"); } - Log.Info("Hot-reloading Lua module: %s", moduleName); + if (__MODULE__ === undefined) { + return $multi(false, "__MODULE__ runtime is not initialized"); + } + + if (__MODULE__.GetModuleByName(moduleName) === undefined) { + Log.Warn("Module '%s' is not loaded yet, skipping hot-reload.", moduleName); + return $multi(false, "Module not loaded: " + moduleName); + } + + Log.Info("Hot-reloading module via __MODULE__: %s", moduleName); EventBus.Emit(EVENT_BEFORE_RELOAD, moduleName); - const [okHr, unluaHr] = pcall(require, "UnLua.HotReload"); - const hrMod = unluaHr as UnLuaHotReloadModule | undefined; - if (okHr && hrMod !== undefined && type(hrMod.reload) === "function") { - const [ok, err] = pcall(hrMod.reload, [moduleName]); - if (!ok) { - Log.Error("UnLua.HotReload.reload('%s') failed: %s", moduleName, tostring(err)); - return $multi(false, err); - } - } else { - GetLuaPackage().loaded[moduleName] = undefined; - const [ok, result] = pcall(require, moduleName); - if (!ok) { - Log.Error("Failed to hot-reload module '%s': %s", moduleName, tostring(result)); - return $multi(false, result); - } + const [ok, err] = __MODULE__.ReimportSafely(moduleName); + if (!ok) { + Log.Error("__MODULE__.ReimportSafely('%s') failed: %s", moduleName, tostring(err)); + return $multi(false, err); } EventBus.Emit(EVENT_AFTER_RELOAD, moduleName); - Log.Info("Successfully hot-reloaded Lua module: %s", moduleName); + Log.Info("Successfully hot-reloaded module: %s", moduleName); return $multi(true); } /** - * Triggers UnLua hot-reload across all loaded Game.* modules (supports Saved/HotUpdate/Script overrides). + * 批量热更所有已加载的业务/框架模块(Game.* / Framework.*)。 */ export function ReloadAll(): boolean { - const gameModules = CollectReloadableGameModules(); - Log.Info("Triggering UnLua HotReload (modules=%d)...", gameModules.length); + const managedModules = CollectLoadedHotReloadModules(); + Log.Info("Triggering HotReload via __MODULE__ (modules=%d)...", managedModules.length); EventBus.Emit(EVENT_BEFORE_RELOAD, "*"); - const [okHr, unluaHr] = pcall(require, "UnLua.HotReload"); - const hrMod = unluaHr as UnLuaHotReloadModule | undefined; - if (okHr && hrMod !== undefined && type(hrMod.reload) === "function") { - if (gameModules.length > 0) { - const [ok, err] = pcall(hrMod.reload, gameModules); - if (!ok) { - Log.Error("UnLua.HotReload.reload(gameModules) failed: %s", tostring(err)); - return false; - } - } - // Also run timestamp-based check for any other modified modules - const [ok2, err2] = pcall(hrMod.reload); - if (!ok2) { - Log.Error("UnLua.HotReload.reload() failed: %s", tostring(err2)); - return false; - } - } else if (UnLua !== undefined && type(UnLua.HotReload) === "function") { - const [ok, err] = pcall(UnLua.HotReload); + let allOk = true; + for (let i = 0; i < managedModules.length; i++) { + const modName = managedModules[i]; + const [ok, err] = __MODULE__.ReimportSafely(modName); if (!ok) { - Log.Error("UnLua.HotReload() failed: %s", tostring(err)); - return false; + Log.Error("__MODULE__.ReimportSafely('%s') failed: %s", modName, tostring(err)); + allOk = false; } - } else { - Log.Warn("UnLua.HotReload is unavailable; skipping global hot reload."); - return false; } EventBus.Emit(EVENT_AFTER_RELOAD, "*"); - Log.Info("UnLua HotReload completed."); - return true; + Log.Info("HotReload completed (ok=%s).", tostring(allOk)); + return allOk; } diff --git a/Script/ts/src/Game/LuaCharacter.ts b/Script/ts/src/Game/LuaCharacter.ts index 05b55d4..33fbedf 100644 --- a/Script/ts/src/Game/LuaCharacter.ts +++ b/Script/ts/src/Game/LuaCharacter.ts @@ -1,12 +1,11 @@ +/** @noSelfInFile */ + import * as Log from "../Framework/Log"; -@unlua -export default class LuaCharacter extends UE.ALuaCharacter { - ReceiveBeginPlay(): void { - Log.Info("LuaCharacter:ReceiveBeginPlay()"); - } +export function OnBeginPlay(_character: UE.ALuaCharacter): void { + Log.Info("LuaCharacter.OnBeginPlay()"); +} - ReceiveEndPlay(EndPlayReason: number): void { - Log.Info("LuaCharacter:ReceiveEndPlay(reason=%s)", tostring(EndPlayReason)); - } +export function OnEndPlay(_character: UE.ALuaCharacter, endPlayReason: number): void { + Log.Info("LuaCharacter.OnEndPlay(reason=%s)", tostring(endPlayReason)); } diff --git a/Script/ts/src/Game/LuaDemoActor.ts b/Script/ts/src/Game/LuaDemoActor.ts index f068dce..dae558b 100644 --- a/Script/ts/src/Game/LuaDemoActor.ts +++ b/Script/ts/src/Game/LuaDemoActor.ts @@ -2,7 +2,7 @@ import * as Log from "../Framework/Log"; import * as EventBus from "../Framework/EventBus"; import * as HotReload from "../Framework/HotReload"; -interface DemoColorEntry { +export interface DemoColorEntry { Name: string; R: number; G: number; @@ -10,7 +10,14 @@ interface DemoColorEntry { A: number; } -const DEMO_COLORS: DemoColorEntry[] = [ +// ============================================================ +// PIE 单文件热更测试参数区(修改此处 -> npm run build -> 触发热更,即时生效) +// ============================================================ +export const DEMO_VERSION = "v1"; +/** 目标旋转速度(度/秒,直接驱动方块自转速度,热更后下一帧立即生效) */ +export const ACTOR_SPIN_SPEED = 60.0; +/** 当前展示配色(热更修改颜色值与名称后,__module.OnReimport 立即刷新方块材质与 3D 文本) */ +export const DEMO_COLORS: DemoColorEntry[] = [ { Name: "Cyan", R: 0.08, G: 0.78, B: 0.95, A: 1.0 }, { Name: "Gold", R: 0.98, G: 0.72, B: 0.12, A: 1.0 }, { Name: "Magenta", R: 0.92, G: 0.22, B: 0.65, A: 1.0 }, @@ -23,41 +30,73 @@ function MakeLinearColor(c: DemoColorEntry): UE.FLinearColor { return UE.FLinearColor(c.R, c.G, c.B, c.A); } -@unlua -export default class LuaDemoActor extends UE.ALuaDemoActor { - private ElapsedTime!: number; - private TextRefreshTimer!: number; - private TickCount!: number; - private PingCount!: number; - private ReloadCount!: number; - private ColorIndex!: number; - private HasLoggedTick!: boolean; - private _tmpDeltaRot!: UE.FRotator; +/** @noSelf */ +function IsActorAlive(actor: UE.ALuaDemoActor | undefined): boolean { + if (actor === undefined) { + return false; + } + if (UE !== undefined && UE.UKismetSystemLibrary !== undefined && UE.UKismetSystemLibrary.IsValid !== undefined) { + return UE.UKismetSystemLibrary.IsValid(actor); + } + return true; +} - ReceiveBeginPlay(): void { - this.ElapsedTime = 0.0; - this.TextRefreshTimer = 0.0; - this.TickCount = 0; - this.PingCount = 0; - this.ReloadCount = 0; - this.ColorIndex = 0; - this.HasLoggedTick = false; +/** + * 纯 TS 组合控制器(不继承 UE 对象、不使用 @unlua): + * 组合持有 `UE.ALuaDemoActor` 引用,由 `Lib/Class.lua` 的 `__TS__DefineClass` 托管原型表, + * 支持单文件热更 `Game.LuaDemoActor` 时在运行中实例上原地更新旋转速度、颜色与全部方法逻辑。 + */ +export class DemoActorController { + private actor: UE.ALuaDemoActor; + private elapsedTime = 0.0; + private textRefreshTimer = 0.0; + private tickCount = 0; + private pingCount = 0; + private reloadCount = 0; + private colorIndex = 0; + private hasLoggedTick = false; + private _tmpDeltaRot: UE.FRotator; + + constructor(actor: UE.ALuaDemoActor) { + this.actor = actor; this._tmpDeltaRot = UE.FRotator(0.0, 0.0, 0.0); + } + IsValid(): boolean { + return IsActorAlive(this.actor); + } + + GetSpinSpeed(): number { + return ACTOR_SPIN_SPEED; + } + + GetCurrentColor(): DemoColorEntry { + return DEMO_COLORS[this.colorIndex] ?? DEMO_COLORS[0]; + } + + OnBeginPlay(): void { EventBus.On("Demo.Ping", this.OnDemoPing, this); EventBus.On(HotReload.EVENT_AFTER_RELOAD, this.OnAfterHotReload, this); this.ApplyCurrentColor(); this.RefreshStatusText(); - Log.Info("LuaDemoActor:ReceiveBeginPlay() bound successfully! Lua=%s", _VERSION); - - const msg = string.format( - "[UnLua Demo] LuaDemoActor active (%s) - Press [Space] to Ping, [R] to HotReload", + Log.Info( + "LuaDemoActor.OnBeginPlay() ready! version=%s speed=%.1f color=%s Lua=%s", + DEMO_VERSION, + this.GetSpinSpeed(), + this.GetCurrentColor().Name, _VERSION ); + + const msg = string.format( + "[UnLua Demo] Pure-TS Actor active (%s | Speed=%.0f | Color=%s) - [Space] Ping, [R] HotReload", + DEMO_VERSION, + this.GetSpinSpeed(), + this.GetCurrentColor().Name + ); UE.UKismetSystemLibrary.PrintString( - this, + this.actor, msg, true, true, @@ -66,65 +105,67 @@ export default class LuaDemoActor extends UE.ALuaDemoActor { ); } - ReceiveTick(DeltaSeconds: number): void { - this.ElapsedTime = (this.ElapsedTime ?? 0.0) + DeltaSeconds; - this.TickCount = (this.TickCount ?? 0) + 1; + OnTick(deltaSeconds: number): void { + this.elapsedTime = this.elapsedTime + deltaSeconds; + this.tickCount = this.tickCount + 1; - if (!this.HasLoggedTick) { - this.HasLoggedTick = true; - Log.Info("LuaDemoActor:ReceiveTick() first tick verified (dt=%.4f)", DeltaSeconds); + if (!this.hasLoggedTick) { + this.hasLoggedTick = true; + Log.Info("LuaDemoActor.OnTick() first tick verified (dt=%.4f, speed=%.1f)", deltaSeconds, this.GetSpinSpeed()); } - // Rotate cube mesh & apply vertical sine-wave bobbing entirely from Lua - const yawDelta = (this.SpinSpeed ?? 60.0) * DeltaSeconds; + const yawDelta = this.GetSpinSpeed() * deltaSeconds; const pitchDelta = yawDelta * 0.35; - if (!this._tmpDeltaRot) { - this._tmpDeltaRot = UE.FRotator(pitchDelta, yawDelta, 0.0); - } else { - this._tmpDeltaRot.Pitch = pitchDelta; - this._tmpDeltaRot.Yaw = yawDelta; - this._tmpDeltaRot.Roll = 0.0; - } - this.AddCubeLocalRotation(this._tmpDeltaRot); + this._tmpDeltaRot.Pitch = pitchDelta; + this._tmpDeltaRot.Yaw = yawDelta; + this._tmpDeltaRot.Roll = 0.0; + this.actor.AddCubeLocalRotation(this._tmpDeltaRot); - const zOffset = math.sin(this.ElapsedTime * (this.BobFrequency ?? 2.0)) * (this.BobAmplitude ?? 25.0); - this.SetCubeVerticalOffset(zOffset); + const zOffset = math.sin(this.elapsedTime * (this.actor.BobFrequency ?? 2.0)) * (this.actor.BobAmplitude ?? 25.0); + this.actor.SetCubeVerticalOffset(zOffset); - this.TextRefreshTimer = (this.TextRefreshTimer ?? 0.0) + DeltaSeconds; - if (this.TextRefreshTimer >= 0.2) { - this.TextRefreshTimer = 0.0; + this.textRefreshTimer = this.textRefreshTimer + deltaSeconds; + if (this.textRefreshTimer >= 0.2) { + this.textRefreshTimer = 0.0; this.RefreshStatusText(); } } OnDemoPing(sourceName: unknown): void { - this.PingCount = (this.PingCount ?? 0) + 1; - this.ColorIndex = ((this.ColorIndex ?? 0) + 1) % DEMO_COLORS.length; + this.pingCount = this.pingCount + 1; + globalPingCount = globalPingCount + 1; + this.colorIndex = (this.colorIndex + 1) % DEMO_COLORS.length; const colorEntry = this.ApplyCurrentColor(); this.RefreshStatusText(); const msg = string.format( - "[UnLua Demo] Ping #%d from %s -> Cube color: %s", - this.PingCount, + "[UnLua Demo] Ping #%d from %s -> Cube color: %s (Speed=%.0f)", + this.pingCount, tostring(sourceName), - colorEntry.Name + colorEntry.Name, + this.GetSpinSpeed() ); Log.Info(msg); - UE.UKismetSystemLibrary.PrintString(this, msg, true, true, MakeLinearColor(colorEntry), 3.0); + UE.UKismetSystemLibrary.PrintString(this.actor, msg, true, true, MakeLinearColor(colorEntry), 3.0); } OnAfterHotReload(moduleName: unknown): void { - this.ReloadCount = (this.ReloadCount ?? 0) + 1; + this.reloadCount = this.reloadCount + 1; + globalReloadCount = globalReloadCount + 1; + this.ApplyCurrentColor(); this.RefreshStatusText(); const msg = string.format( - "[UnLua Demo] HotReload #%d completed (target=%s)", - this.ReloadCount, - tostring(moduleName) + "[UnLua Demo] HotReload #%d applied! target=%s | version=%s | Speed=%.0f | Color=%s", + this.reloadCount, + tostring(moduleName), + DEMO_VERSION, + this.GetSpinSpeed(), + this.GetCurrentColor().Name ); Log.Info(msg); UE.UKismetSystemLibrary.PrintString( - this, + this.actor, msg, true, true, @@ -133,27 +174,125 @@ export default class LuaDemoActor extends UE.ALuaDemoActor { ); } + ResetToPrimaryColor(): void { + this.colorIndex = 0; + } + ApplyCurrentColor(): DemoColorEntry { - const colorEntry = DEMO_COLORS[this.ColorIndex ?? 0] ?? DEMO_COLORS[0]; - this.SetCubeColor(MakeLinearColor(colorEntry)); + const colorEntry = this.GetCurrentColor(); + this.actor.SetCubeColor(MakeLinearColor(colorEntry)); return colorEntry; } RefreshStatusText(): void { - const colorEntry = DEMO_COLORS[this.ColorIndex ?? 0] ?? DEMO_COLORS[0]; + const colorEntry = this.GetCurrentColor(); const text = string.format( - "UnLua Active (%s)\nTime: %.1fs | Pings: %d | Reloads: %d | Color: %s\n[Space] Ping Lua | [R] HotReload", + "Pure-TS Actor (%s | %s)\nSpeed: %.0f deg/s | Color: %s\nTime: %.1fs | Pings: %d | Reloads: %d\n[Space] Ping | [R] HotReload", _VERSION, - this.ElapsedTime ?? 0.0, - this.PingCount ?? 0, - this.ReloadCount ?? 0, - colorEntry.Name + DEMO_VERSION, + this.GetSpinSpeed(), + colorEntry.Name, + this.elapsedTime, + this.pingCount, + this.reloadCount ); - this.SetStatusText(text); + this.actor.SetStatusText(text); } - ReceiveEndPlay(EndPlayReason: number): void { + OnEndPlay(_endPlayReason: number): void { EventBus.OffAllForOwner(this); - Log.Info("LuaDemoActor:ReceiveEndPlay(ticks=%d, pings=%d)", this.TickCount ?? 0, this.PingCount ?? 0); + Log.Info("LuaDemoActor.OnEndPlay(ticks=%d, pings=%d)", this.tickCount, this.pingCount); } } + +/** 跨热更保留的运行中控制器映射表(key = actor:GetName()) */ +/** @module_data */ +const activeControllers: Record = {}; + +/** @module_data */ +let globalPingCount = 0; + +/** @module_data */ +let globalReloadCount = 0; + +/** @noSelf */ +function GetActorKey(actor: UE.ALuaDemoActor): string { + if (actor.GetName !== undefined) { + return actor.GetName(); + } + return tostring(actor); +} + +/** @noSelf */ +export function OnBeginPlay(actor: UE.ALuaDemoActor): void { + const key = GetActorKey(actor); + const old = activeControllers[key]; + if (old !== undefined) { + old.OnEndPlay(0); + } + const ctrl = new DemoActorController(actor); + activeControllers[key] = ctrl; + ctrl.OnBeginPlay(); +} + +/** @noSelf */ +export function OnTick(actor: UE.ALuaDemoActor, deltaSeconds: number): void { + const ctrl = activeControllers[GetActorKey(actor)]; + if (ctrl !== undefined) { + ctrl.OnTick(deltaSeconds); + } +} + +/** @noSelf */ +export function OnEndPlay(actor: UE.ALuaDemoActor, endPlayReason: number): void { + const key = GetActorKey(actor); + const ctrl = activeControllers[key]; + if (ctrl !== undefined) { + ctrl.OnEndPlay(endPlayReason); + activeControllers[key] = undefined; + } +} + +/** @noSelf */ +export function GetGlobalStats(): { pings: number; reloads: number; version: string; spinSpeed: number; primaryColor: string } { + return { + pings: globalPingCount, + reloads: globalReloadCount, + version: DEMO_VERSION, + spinSpeed: ACTOR_SPIN_SPEED, + primaryColor: DEMO_COLORS[0].Name, + }; +} + +/** @noSelf */ +export function GetActiveControllerCount(): number { + let count = 0; + for (const [_, ctrl] of pairs(activeControllers)) { + if (ctrl !== undefined) { + count = count + 1; + } + } + return count; +} + +// 模块单文件热更完成后立即将新的颜色、旋转速度与 3D 文本应用到 PIE 中所有活跃 Actor +__module.OnReimport = () => { + for (const [key, ctrl] of pairs(activeControllers)) { + if (ctrl !== undefined) { + if (ctrl.IsValid()) { + ctrl.ResetToPrimaryColor(); + ctrl.ApplyCurrentColor(); + ctrl.RefreshStatusText(); + } else { + activeControllers[key] = undefined; + } + } + } + Log.Info( + "Game.LuaDemoActor OnReimport applied! version=%s speed=%.1f color=%s activeActors=%d", + DEMO_VERSION, + ACTOR_SPIN_SPEED, + DEMO_COLORS[0].Name, + GetActiveControllerCount() + ); +}; diff --git a/Script/ts/src/Game/LuaGameInstance.ts b/Script/ts/src/Game/LuaGameInstance.ts index 2fb4998..8bf59e6 100644 --- a/Script/ts/src/Game/LuaGameInstance.ts +++ b/Script/ts/src/Game/LuaGameInstance.ts @@ -1,15 +1,14 @@ +/** @noSelfInFile */ + import * as Bootstrap from "../Framework/Bootstrap"; import * as Log from "../Framework/Log"; -@unlua -export default class LuaGameInstance extends UE.ULuaGameInstance { - ReceiveInit(): void { - Bootstrap.Init(this); - Log.Info("LuaGameInstance:ReceiveInit()"); - } +export function OnInit(gameInstance: UE.ULuaGameInstance): void { + Bootstrap.Init(gameInstance); + Log.Info("LuaGameInstance.OnInit()"); +} - ReceiveShutdown(): void { - Log.Info("LuaGameInstance:ReceiveShutdown()"); - Bootstrap.Shutdown(); - } +export function OnShutdown(_gameInstance: UE.ULuaGameInstance): void { + Log.Info("LuaGameInstance.OnShutdown()"); + Bootstrap.Shutdown(); } diff --git a/Script/ts/src/Game/LuaGameMode.ts b/Script/ts/src/Game/LuaGameMode.ts index 59002ed..11c8400 100644 --- a/Script/ts/src/Game/LuaGameMode.ts +++ b/Script/ts/src/Game/LuaGameMode.ts @@ -1,20 +1,19 @@ +/** @noSelfInFile */ + import * as Log from "../Framework/Log"; -@unlua -export default class LuaGameMode extends UE.ALuaGameModeBase { - ReceiveBeginPlay(): void { - Log.Info("LuaGameMode:ReceiveBeginPlay() - Demo scene started"); - UE.UKismetSystemLibrary.PrintString( - this, - "[UnLua Demo] LuaGameMode initialized!", - true, - true, - UE.FLinearColor(0.3, 0.85, 1.0, 1.0), - 5.0 - ); - } +export function OnBeginPlay(gameMode: UE.ALuaGameModeBase): void { + Log.Info("LuaGameMode.OnBeginPlay() - Demo scene started"); + UE.UKismetSystemLibrary.PrintString( + gameMode, + "[UnLua Demo] LuaGameMode initialized (Pure TS Callback Mode)!", + true, + true, + UE.FLinearColor(0.3, 0.85, 1.0, 1.0), + 5.0 + ); +} - ReceiveEndPlay(EndPlayReason: number): void { - Log.Info("LuaGameMode:ReceiveEndPlay(reason=%s)", tostring(EndPlayReason)); - } +export function OnEndPlay(_gameMode: UE.ALuaGameModeBase, endPlayReason: number): void { + Log.Info("LuaGameMode.OnEndPlay(reason=%s)", tostring(endPlayReason)); } diff --git a/Script/ts/src/Game/LuaPlayerController.ts b/Script/ts/src/Game/LuaPlayerController.ts index bd09814..02cf8f8 100644 --- a/Script/ts/src/Game/LuaPlayerController.ts +++ b/Script/ts/src/Game/LuaPlayerController.ts @@ -1,24 +1,23 @@ +/** @noSelfInFile */ + import * as Log from "../Framework/Log"; import * as EventBus from "../Framework/EventBus"; import * as HotReload from "../Framework/HotReload"; -@unlua -export default class LuaPlayerController extends UE.ALuaPlayerController { - ReceiveBeginPlay(): void { - Log.Info("LuaPlayerController:ReceiveBeginPlay() - Ready for [Space]=Ping, [R]=HotReload"); - } +export function OnBeginPlay(_pc: UE.ALuaPlayerController): void { + Log.Info("LuaPlayerController.OnBeginPlay() - Ready for [Space]=Ping, [R]=HotReload"); +} - OnDemoPingPressed(): void { - Log.Info("LuaPlayerController:OnDemoPingPressed() -> Emitting Demo.Ping"); - EventBus.Emit("Demo.Ping", "LuaPlayerController"); - } +export function OnDemoPingPressed(_pc: UE.ALuaPlayerController): void { + Log.Info("LuaPlayerController.OnDemoPingPressed() -> Emitting Demo.Ping"); + EventBus.Emit("Demo.Ping", "LuaPlayerController"); +} - OnDemoHotReloadPressed(): void { - Log.Info("LuaPlayerController:OnDemoHotReloadPressed() -> Triggering HotReload.ReloadAll()"); - HotReload.ReloadAll(); - } +export function OnDemoHotReloadPressed(_pc: UE.ALuaPlayerController): void { + Log.Info("LuaPlayerController.OnDemoHotReloadPressed() -> Triggering HotReload.ReloadAll()"); + HotReload.ReloadAll(); +} - ReceiveEndPlay(EndPlayReason: number): void { - Log.Info("LuaPlayerController:ReceiveEndPlay(reason=%s)", tostring(EndPlayReason)); - } +export function OnEndPlay(_pc: UE.ALuaPlayerController, endPlayReason: number): void { + Log.Info("LuaPlayerController.OnEndPlay(reason=%s)", tostring(endPlayReason)); } diff --git a/Script/ts/src/Tests/Extra/HotReloadAndFrameworkTest.ts b/Script/ts/src/Tests/Extra/HotReloadAndFrameworkTest.ts index 7ad130c..a6df83d 100644 --- a/Script/ts/src/Tests/Extra/HotReloadAndFrameworkTest.ts +++ b/Script/ts/src/Tests/Extra/HotReloadAndFrameworkTest.ts @@ -14,7 +14,7 @@ import { CreateBoundInstance, ResetMockState } from "../Harness/MockUnLuaRuntime import * as Bootstrap from "../../Framework/Bootstrap"; import * as EventBus from "../../Framework/EventBus"; import * as HotReload from "../../Framework/HotReload"; -import LuaDemoActor from "../../Game/LuaDemoActor"; +import * as LuaDemoActor from "../../Game/LuaDemoActor"; export function RunHotReloadAndFrameworkTests(): void { Suite("Extra.FrameworkAndHotReload", () => { @@ -105,7 +105,7 @@ export function RunHotReloadAndFrameworkTests(): void { EventBus.Clear(); }); - Test("LuaDemoActor full integration: BeginPlay, Tick, Ping color cycle, HotReload event & EndPlay cleanup", () => { + Test("LuaDemoActor full integration: pure TS callback BeginPlay, Tick, Ping color cycle, HotReload & EndPlay cleanup", () => { ResetMockState(); EventBus.Clear(); @@ -114,8 +114,8 @@ export function RunHotReloadAndFrameworkTests(): void { let rotationAddCount = 0; let lastVerticalOffset = 0; - const demoActor = CreateBoundInstance( - LuaDemoActor as unknown as Record, + const fakeActor = CreateBoundInstance( + {}, "ALuaDemoActor", { SpinSpeed: 90, @@ -136,11 +136,12 @@ export function RunHotReloadAndFrameworkTests(): void { } ); - demoActor.ReceiveBeginPlay(); + LuaDemoActor.OnBeginPlay(fakeActor); AssertEqual(colorApplyCount, 1); AssertTrue(string.find(lastStatusText, "Pings: 0", 1, true)[0] !== undefined); + AssertTrue(string.find(lastStatusText, "Speed: 60", 1, true)[0] !== undefined); - demoActor.ReceiveTick(0.25); + LuaDemoActor.OnTick(fakeActor, 0.25); AssertEqual(rotationAddCount, 1); AssertTrue(lastVerticalOffset !== 0); @@ -149,12 +150,13 @@ export function RunHotReloadAndFrameworkTests(): void { AssertTrue(string.find(lastStatusText, "Pings: 1", 1, true)[0] !== undefined); EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, "Game.LuaDemoActor"); + AssertEqual(colorApplyCount, 3); AssertTrue(string.find(lastStatusText, "Reloads: 1", 1, true)[0] !== undefined); // EndPlay 后不再响应 EventBus - demoActor.ReceiveEndPlay(UE.EEndPlayReason.Destroyed); + LuaDemoActor.OnEndPlay(fakeActor, UE.EEndPlayReason.Destroyed); EventBus.Emit("Demo.Ping", "AfterEndPlay"); - AssertEqual(colorApplyCount, 2); + AssertEqual(colorApplyCount, 3); EventBus.Clear(); }); }); diff --git a/Script/ts/src/Tests/UE/UERuntimeSuite.ts b/Script/ts/src/Tests/UE/UERuntimeSuite.ts index a2122d9..b8a2ab5 100644 --- a/Script/ts/src/Tests/UE/UERuntimeSuite.ts +++ b/Script/ts/src/Tests/UE/UERuntimeSuite.ts @@ -236,7 +236,7 @@ export function RunUERuntimeSuite(world: UE.UWorld): void { UnLua.Unref(obj); }); - Test("Real UE ALuaDemoActor (IUnLuaInterface static binding) + EventBus + Tick + EndPlay", () => { + Test("Real UE ALuaDemoActor (C++ callback -> pure TS Game.LuaDemoActor) + EventBus + Tick + EndPlay", () => { // 不调用 EventBus.Clear(),避免在 PIE 关卡中误清场景里已运行的 LuaDemoActor 监听 const demoActor = world.SpawnActor( UE.ALuaDemoActor.StaticClass(), @@ -246,9 +246,9 @@ export function RunUERuntimeSuite(world: UE.UWorld): void { AssertNotNil(demoActor); AssertTrue(demoActor!.IsA(UE.ALuaDemoActor.StaticClass())); - // Spawn 时已自动通过 IUnLuaInterface 绑定 Game.LuaDemoActor 并执行 ReceiveBeginPlay + // Spawn 时已通过 C++ FLuaCallbackBridge 回调 Game.LuaDemoActor.OnBeginPlay const initText = demoActor!.GetStatusTextString(); - AssertTrue(string.find(initText, "UnLua Active", 1, true)[0] !== undefined); + AssertTrue(string.find(initText, "Pure-TS Actor", 1, true)[0] !== undefined, "initText: " + initText); AssertTrue(string.find(initText, "Pings: 0", 1, true)[0] !== undefined); if (canTickWorld) { @@ -337,6 +337,74 @@ export function RunUERuntimeSuite(world: UE.UWorld): void { const [ok] = HotReload.ReloadModule("Framework.Log"); AssertTrue(ok); }); + + Test("Real UE single-file __MODULE__.Reimport hot-reloads Game.LuaDemoActor spin speed and color live", () => { + const demoActor = world.SpawnActor( + UE.ALuaDemoActor.StaticClass(), + UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 200), UE.FVector(1, 1, 1)), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn + ); + AssertNotNil(demoActor); + + const beforeText = demoActor!.GetStatusTextString(); + AssertTrue(string.find(beforeText, "v1", 1, true)[0] !== undefined); + AssertTrue(string.find(beforeText, "Speed: 60", 1, true)[0] !== undefined); + AssertTrue(string.find(beforeText, "Color: Cyan", 1, true)[0] !== undefined); + + const actorMod = __MODULE__.Import("Game.LuaDemoActor"); + const activeBefore: number = actorMod.GetActiveControllerCount(); + AssertTrue(activeBefore >= 1); + + // 模拟修改 Game/LuaDemoActor.lua 的旋转速度与颜色,写入热更覆盖目录并触发单文件热更 + const defaultDir = UE.ULuaHotUpdateSubsystem.GetDefaultScriptDir(); + const overrideDir = UE.ULuaHotUpdateSubsystem.GetHotUpdateScriptDir(); + const srcPath = defaultDir + "/Game/LuaDemoActor.lua"; + const dstGameDir = overrideDir + "/Game"; + const dstPath = dstGameDir + "/LuaDemoActor.lua"; + + const srcFile = io.open(srcPath, "rb")[0]; + AssertNotNil(srcFile); + const origLua = srcFile!.read("a") as string; + srcFile!.close(); + + let [patchedLua] = string.gsub(origLua, '"v1"', '"v2-HOTFIX"'); + [patchedLua] = string.gsub(patchedLua, "ACTOR_SPIN_SPEED = 60", "ACTOR_SPIN_SPEED = 240"); + [patchedLua] = string.gsub(patchedLua, '"Cyan"', '"Crimson"'); + [patchedLua] = string.gsub(patchedLua, "R = 0%.08", "R = 0.95"); + [patchedLua] = string.gsub(patchedLua, "G = 0%.78", "G = 0.12"); + [patchedLua] = string.gsub(patchedLua, "B = 0%.95", "B = 0.18"); + os.execute(string.format('mkdir -p "%s"', dstGameDir)); + const dstFile = io.open(dstPath, "wb")[0]; + AssertNotNil(dstFile); + dstFile!.write(patchedLua); + dstFile!.close(); + + const [okReload, errReload] = HotReload.ReloadModule("Game.LuaDemoActor"); + // 立即清理临时覆盖文件,避免断言失败时残留覆盖文件污染后续运行 + os.remove(dstPath); + AssertTrue(okReload, tostring(errReload)); + + // 1. 模块导出即时更新且 @module_data 活跃控制器表完整保留 + AssertEqual(actorMod.DEMO_VERSION, "v2-HOTFIX"); + AssertEqual(actorMod.ACTOR_SPIN_SPEED, 240); + AssertEqual(actorMod.GetActiveControllerCount(), activeBefore); + // 2. 运行中 Actor 的颜色与 3D 状态文本已通过 __module.OnReimport 即时刷新 + const newColor = demoActor!.GetCubeColor(); + AssertNear(newColor.R, 0.95, 1e-2); + AssertNear(newColor.G, 0.12, 1e-2); + const afterText = demoActor!.GetStatusTextString(); + AssertTrue(string.find(afterText, "v2-HOTFIX", 1, true)[0] !== undefined, "afterText: " + afterText); + AssertTrue(string.find(afterText, "Speed: 240", 1, true)[0] !== undefined, "afterText: " + afterText); + AssertTrue(string.find(afterText, "Color: Crimson", 1, true)[0] !== undefined, "afterText: " + afterText); + + // 热更还原 + const [okRestore] = HotReload.ReloadModule("Game.LuaDemoActor"); + AssertTrue(okRestore); + AssertEqual(actorMod.DEMO_VERSION, "v1"); + AssertEqual(actorMod.ACTOR_SPIN_SPEED, 60); + + demoActor!.K2_DestroyActor(); + }); }); } diff --git a/Script/ts/types/project.d.ts b/Script/ts/types/project.d.ts index b93ea08..552b14d 100644 --- a/Script/ts/types/project.d.ts +++ b/Script/ts/types/project.d.ts @@ -14,3 +14,9 @@ interface LuaPackageTable { declare var GameFramework: Record | undefined; declare var __UE_TEST_WORLD: UE.UWorld | undefined; declare var __UE_TEST_TICK: ((this: void, deltaSeconds: number) => void) | undefined; + +declare namespace UE { + interface ALuaDemoActor { + GetCubeColor(): FLinearColor; + } +} diff --git a/Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp new file mode 100644 index 0000000..fdd9108 --- /dev/null +++ b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp @@ -0,0 +1,186 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "Core/LuaCallbackBridge.h" +#include "UnrealLuaDemo.h" +#include "Engine/World.h" +#include "Modules/ModuleManager.h" +#include "UnLua.h" +#include "UnLuaModule.h" +#include "LuaEnv.h" +#include "lua.hpp" + +namespace +{ + UnLua::FLuaEnv* ResolveLuaEnv(UObject* Target) + { + if (!Target || Target->HasAnyFlags(RF_ClassDefaultObject | RF_ArchetypeObject)) + { + return nullptr; + } + + // Actor 类仅在真实游戏/PIE 世界中分发回调,避免编辑器视口预览对象误触发 + if (const AActor* Actor = Cast(Target)) + { + const UWorld* World = Actor->GetWorld(); + if (!World || !World->IsGameWorld()) + { + return nullptr; + } + } + + if (FModuleManager::Get().IsModuleLoaded(TEXT("UnLua"))) + { + IUnLuaModule& UnLuaModule = IUnLuaModule::Get(); + if (UnLuaModule.IsActive()) + { + if (UnLua::FLuaEnv* Env = UnLuaModule.GetEnv(Target)) + { + return Env; + } + } + } + + TMap& AllEnvs = UnLua::FLuaEnv::GetAll(); + for (const TPair& Pair : AllEnvs) + { + if (Pair.Value) + { + return Pair.Value; + } + } + + return nullptr; + } + + bool PushModuleFunction(lua_State* L, const FString& ModuleName, const char* FuncName, int32& OutErrHandlerIdx) + { + lua_pushcfunction(L, UnLua::ReportLuaCallError); + OutErrHandlerIdx = lua_gettop(L); + + lua_getglobal(L, "__MODULE__"); + if (!lua_istable(L, -1)) + { + lua_pop(L, 2); + return false; + } + + lua_getfield(L, -1, "Import"); + if (!lua_isfunction(L, -1)) + { + lua_pop(L, 3); + return false; + } + + const FTCHARToUTF8 ModNameUtf8(*ModuleName); + lua_pushlstring(L, ModNameUtf8.Get(), ModNameUtf8.Length()); + if (lua_pcall(L, 1, 1, OutErrHandlerIdx) != LUA_OK) + { + lua_pop(L, 3); // error, __MODULE__, errHandler + return false; + } + + // stack: errHandler, __MODULE__, M + lua_remove(L, -2); // stack: errHandler, M + if (!lua_istable(L, -1)) + { + lua_pop(L, 2); + return false; + } + + lua_getfield(L, -1, FuncName); + lua_remove(L, -2); // stack: errHandler, fn + if (!lua_isfunction(L, -1)) + { + lua_pop(L, 2); + return false; + } + + return true; + } +} + +bool FLuaCallbackBridge::Call(UObject* Target, const FString& ModuleName, const char* FuncName) +{ + UnLua::FLuaEnv* Env = ResolveLuaEnv(Target); + if (!Env) + { + return false; + } + + lua_State* L = Env->GetMainState(); + if (!L) + { + return false; + } + + const int32 Top = lua_gettop(L); + int32 ErrHandlerIdx = 0; + if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx)) + { + lua_settop(L, Top); + return false; + } + + UnLua::PushUObject(L, Target); + const bool bOk = (lua_pcall(L, 1, 0, ErrHandlerIdx) == LUA_OK); + lua_settop(L, Top); + return bOk; +} + +bool FLuaCallbackBridge::CallFloat(UObject* Target, const FString& ModuleName, const char* FuncName, float Value) +{ + UnLua::FLuaEnv* Env = ResolveLuaEnv(Target); + if (!Env) + { + return false; + } + + lua_State* L = Env->GetMainState(); + if (!L) + { + return false; + } + + const int32 Top = lua_gettop(L); + int32 ErrHandlerIdx = 0; + if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx)) + { + lua_settop(L, Top); + return false; + } + + UnLua::PushUObject(L, Target); + lua_pushnumber(L, static_cast(Value)); + const bool bOk = (lua_pcall(L, 2, 0, ErrHandlerIdx) == LUA_OK); + lua_settop(L, Top); + return bOk; +} + +bool FLuaCallbackBridge::CallInt(UObject* Target, const FString& ModuleName, const char* FuncName, int32 Value) +{ + UnLua::FLuaEnv* Env = ResolveLuaEnv(Target); + if (!Env) + { + return false; + } + + lua_State* L = Env->GetMainState(); + if (!L) + { + return false; + } + + const int32 Top = lua_gettop(L); + int32 ErrHandlerIdx = 0; + if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx)) + { + lua_settop(L, Top); + return false; + } + + UnLua::PushUObject(L, Target); + lua_pushinteger(L, static_cast(Value)); + const bool bOk = (lua_pcall(L, 2, 0, ErrHandlerIdx) == LUA_OK); + lua_settop(L, Top); + return bOk; +} diff --git a/Source/UnrealLuaDemo/Core/LuaCallbackBridge.h b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.h new file mode 100644 index 0000000..16a66bd --- /dev/null +++ b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.h @@ -0,0 +1,21 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" + +class UObject; + +/** + * 极薄 C++ -> Lua 回调分发器: + * 通过 __MODULE__.Import(ModuleName)[FuncName](Target, ...) 直接调用纯 TS/Lua 模块, + * 业务脚本无需在 Lua 中继承 UE 对象(不使用 IUnLuaInterface / UnLua.Class), + * 100% 纳入 Lib/Module.lua 与 Lib/Class.lua 的单文件热更闭环。 + */ +class UNREALLUADEMO_API FLuaCallbackBridge +{ +public: + static bool Call(UObject* Target, const FString& ModuleName, const char* FuncName); + static bool CallFloat(UObject* Target, const FString& ModuleName, const char* FuncName, float Value); + static bool CallInt(UObject* Target, const FString& ModuleName, const char* FuncName, int32 Value); +}; diff --git a/Source/UnrealLuaDemo/Core/LuaCharacter.cpp b/Source/UnrealLuaDemo/Core/LuaCharacter.cpp index 3574dfb..2c8faf2 100644 --- a/Source/UnrealLuaDemo/Core/LuaCharacter.cpp +++ b/Source/UnrealLuaDemo/Core/LuaCharacter.cpp @@ -1,13 +1,21 @@ // Copyright Epic Games, Inc. All Rights Reserved. #include "Core/LuaCharacter.h" +#include "Core/LuaCallbackBridge.h" ALuaCharacter::ALuaCharacter() { PrimaryActorTick.bCanEverTick = false; } -FString ALuaCharacter::GetModuleName_Implementation() const +void ALuaCharacter::BeginPlay() { - return LuaModuleName; + Super::BeginPlay(); + FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay"); +} + +void ALuaCharacter::EndPlay(const EEndPlayReason::Type EndPlayReason) +{ + FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast(EndPlayReason)); + Super::EndPlay(EndPlayReason); } diff --git a/Source/UnrealLuaDemo/Core/LuaCharacter.h b/Source/UnrealLuaDemo/Core/LuaCharacter.h index b4b456c..3a16823 100644 --- a/Source/UnrealLuaDemo/Core/LuaCharacter.h +++ b/Source/UnrealLuaDemo/Core/LuaCharacter.h @@ -4,21 +4,21 @@ #include "CoreMinimal.h" #include "GameFramework/Character.h" -#include "UnLuaInterface.h" #include "LuaCharacter.generated.h" /** - * Base Character bound to Lua (Script/lua/Game/LuaCharacter.lua). + * C++ 薄桥接 Character:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaCharacter。 */ UCLASS() -class UNREALLUADEMO_API ALuaCharacter : public ACharacter, public IUnLuaInterface +class UNREALLUADEMO_API ALuaCharacter : public ACharacter { GENERATED_BODY() public: ALuaCharacter(); - virtual FString GetModuleName_Implementation() const override; + virtual void BeginPlay() override; + virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; protected: UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") diff --git a/Source/UnrealLuaDemo/Core/LuaGameInstance.cpp b/Source/UnrealLuaDemo/Core/LuaGameInstance.cpp index 48b84d0..08508ed 100644 --- a/Source/UnrealLuaDemo/Core/LuaGameInstance.cpp +++ b/Source/UnrealLuaDemo/Core/LuaGameInstance.cpp @@ -1,21 +1,19 @@ // Copyright Epic Games, Inc. All Rights Reserved. #include "Core/LuaGameInstance.h" +#include "Core/LuaCallbackBridge.h" #include "UnrealLuaDemo.h" void ULuaGameInstance::Init() { Super::Init(); UE_LOG(LogUnrealLuaDemo, Log, TEXT("ULuaGameInstance::Init() - LuaModule=%s"), *LuaModuleName); + FLuaCallbackBridge::Call(this, LuaModuleName, "OnInit"); } void ULuaGameInstance::Shutdown() { UE_LOG(LogUnrealLuaDemo, Log, TEXT("ULuaGameInstance::Shutdown()")); + FLuaCallbackBridge::Call(this, LuaModuleName, "OnShutdown"); Super::Shutdown(); } - -FString ULuaGameInstance::GetModuleName_Implementation() const -{ - return LuaModuleName; -} diff --git a/Source/UnrealLuaDemo/Core/LuaGameInstance.h b/Source/UnrealLuaDemo/Core/LuaGameInstance.h index 06e3cad..f24b7ce 100644 --- a/Source/UnrealLuaDemo/Core/LuaGameInstance.h +++ b/Source/UnrealLuaDemo/Core/LuaGameInstance.h @@ -4,14 +4,13 @@ #include "CoreMinimal.h" #include "Engine/GameInstance.h" -#include "UnLuaInterface.h" #include "LuaGameInstance.generated.h" /** - * Base GameInstance bound to Lua (Script/lua/Game/LuaGameInstance.lua). + * C++ 薄桥接 GameInstance:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaGameInstance。 */ UCLASS() -class UNREALLUADEMO_API ULuaGameInstance : public UGameInstance, public IUnLuaInterface +class UNREALLUADEMO_API ULuaGameInstance : public UGameInstance { GENERATED_BODY() @@ -19,10 +18,7 @@ public: virtual void Init() override; virtual void Shutdown() override; - virtual FString GetModuleName_Implementation() const override; - protected: - /** Lua module name bound to this GameInstance (relative to Script/lua). */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") FString LuaModuleName = TEXT("Game.LuaGameInstance"); }; diff --git a/Source/UnrealLuaDemo/Core/LuaGameModeBase.cpp b/Source/UnrealLuaDemo/Core/LuaGameModeBase.cpp index 057e997..c04638f 100644 --- a/Source/UnrealLuaDemo/Core/LuaGameModeBase.cpp +++ b/Source/UnrealLuaDemo/Core/LuaGameModeBase.cpp @@ -3,6 +3,7 @@ #include "Core/LuaGameModeBase.h" #include "Core/LuaPlayerController.h" #include "Core/LuaCharacter.h" +#include "Core/LuaCallbackBridge.h" ALuaGameModeBase::ALuaGameModeBase() { @@ -10,7 +11,14 @@ ALuaGameModeBase::ALuaGameModeBase() DefaultPawnClass = ALuaCharacter::StaticClass(); } -FString ALuaGameModeBase::GetModuleName_Implementation() const +void ALuaGameModeBase::BeginPlay() { - return LuaModuleName; + Super::BeginPlay(); + FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay"); +} + +void ALuaGameModeBase::EndPlay(const EEndPlayReason::Type EndPlayReason) +{ + FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast(EndPlayReason)); + Super::EndPlay(EndPlayReason); } diff --git a/Source/UnrealLuaDemo/Core/LuaGameModeBase.h b/Source/UnrealLuaDemo/Core/LuaGameModeBase.h index 3e337ca..17ac4d9 100644 --- a/Source/UnrealLuaDemo/Core/LuaGameModeBase.h +++ b/Source/UnrealLuaDemo/Core/LuaGameModeBase.h @@ -4,21 +4,21 @@ #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" -#include "UnLuaInterface.h" #include "LuaGameModeBase.generated.h" /** - * Base GameMode bound to Lua (Script/lua/Game/LuaGameMode.lua). + * C++ 薄桥接 GameMode:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaGameMode。 */ UCLASS() -class UNREALLUADEMO_API ALuaGameModeBase : public AGameModeBase, public IUnLuaInterface +class UNREALLUADEMO_API ALuaGameModeBase : public AGameModeBase { GENERATED_BODY() public: ALuaGameModeBase(); - virtual FString GetModuleName_Implementation() const override; + virtual void BeginPlay() override; + virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; protected: UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") diff --git a/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp b/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp index d03f92b..aabc879 100644 --- a/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp +++ b/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp @@ -1,6 +1,7 @@ // Copyright Epic Games, Inc. All Rights Reserved. #include "Core/LuaPlayerController.h" +#include "Core/LuaCallbackBridge.h" #include "Demo/LuaDemoActor.h" #include "UnrealLuaDemo.h" #include "Components/InputComponent.h" @@ -17,6 +18,14 @@ void ALuaPlayerController::BeginPlay() bShowMouseCursor = false; FInputModeGameOnly InputMode; SetInputMode(InputMode); + + FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay"); +} + +void ALuaPlayerController::EndPlay(const EEndPlayReason::Type EndPlayReason) +{ + FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast(EndPlayReason)); + Super::EndPlay(EndPlayReason); } void ALuaPlayerController::SetupInputComponent() @@ -33,21 +42,16 @@ void ALuaPlayerController::SetupInputComponent() } } -FString ALuaPlayerController::GetModuleName_Implementation() const -{ - return LuaModuleName; -} - void ALuaPlayerController::HandlePingKeyPressed() { UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandlePingKeyPressed() -> dispatching OnDemoPingPressed to Lua")); - OnDemoPingPressed(); + FLuaCallbackBridge::Call(this, LuaModuleName, "OnDemoPingPressed"); } void ALuaPlayerController::HandleHotReloadKeyPressed() { UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandleHotReloadKeyPressed() -> dispatching OnDemoHotReloadPressed to Lua")); - OnDemoHotReloadPressed(); + FLuaCallbackBridge::Call(this, LuaModuleName, "OnDemoHotReloadPressed"); } void ALuaPlayerController::DemoVerifyInteraction() diff --git a/Source/UnrealLuaDemo/Core/LuaPlayerController.h b/Source/UnrealLuaDemo/Core/LuaPlayerController.h index 9f64c59..1359d2f 100644 --- a/Source/UnrealLuaDemo/Core/LuaPlayerController.h +++ b/Source/UnrealLuaDemo/Core/LuaPlayerController.h @@ -4,34 +4,21 @@ #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" -#include "UnLuaInterface.h" #include "LuaPlayerController.generated.h" /** - * Base PlayerController bound to Lua (Script/lua/Game/LuaPlayerController.lua). - * Binds demo hotkeys ([Space] Ping Lua, [R] HotReload Lua) and forwards them to Lua via BlueprintImplementableEvent. + * C++ 薄桥接 PlayerController:不实现 IUnLuaInterface,通过 FLuaCallbackBridge + * 将生命周期与按键事件([Space] Ping, [R] HotReload)分发至纯 TS 模块 Game.LuaPlayerController。 */ UCLASS() -class UNREALLUADEMO_API ALuaPlayerController : public APlayerController, public IUnLuaInterface +class UNREALLUADEMO_API ALuaPlayerController : public APlayerController { GENERATED_BODY() public: virtual void BeginPlay() override; + virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; virtual void SetupInputComponent() override; - virtual FString GetModuleName_Implementation() const override; - - /** - * Implemented in LuaPlayerController.lua to test C++ -> Lua -> EventBus flow. - * Note: BlueprintImplementableEvent ensures UE always dispatches through ProcessEvent into UnLua - * (unlike BlueprintNativeEvent on native C++ classes which UHT optimizes to bypass ProcessEvent). - */ - UFUNCTION(BlueprintImplementableEvent, Category = "LuaDemo") - void OnDemoPingPressed(); - - /** Implemented in LuaPlayerController.lua to trigger live Lua hot-reload. */ - UFUNCTION(BlueprintImplementableEvent, Category = "LuaDemo") - void OnDemoHotReloadPressed(); /** Automated self-test command (console: Demo.VerifyInteraction) that simulates Space & R and verifies Tick + Lua state. */ UFUNCTION(Exec) diff --git a/Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp b/Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp index 627a8cb..fa73098 100644 --- a/Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp +++ b/Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp @@ -1,6 +1,7 @@ // Copyright Epic Games, Inc. All Rights Reserved. #include "Demo/LuaDemoActor.h" +#include "Core/LuaCallbackBridge.h" #include "Components/StaticMeshComponent.h" #include "Components/TextRenderComponent.h" #include "Engine/StaticMesh.h" @@ -39,7 +40,7 @@ ALuaDemoActor::ALuaDemoActor() StatusText->SetVerticalAlignment(EVRTA_TextCenter); StatusText->SetWorldSize(26.0f); StatusText->SetTextRenderColor(FColor(120, 245, 255)); - StatusText->SetText(FText::FromString(TEXT("Waiting for UnLua..."))); + StatusText->SetText(FText::FromString(TEXT("Waiting for Lua..."))); } void ALuaDemoActor::BeginPlay() @@ -52,23 +53,22 @@ void ALuaDemoActor::BeginPlay() } Super::BeginPlay(); + + FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay"); } void ALuaDemoActor::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); - // AActor::Tick skips ReceiveTick for pure native C++ classes (CLASS_Native without CLASS_CompiledFromBlueprint). - // Explicitly call ReceiveTick so UnLua's Lua ReceiveTick override executes every frame. - if (!GetClass()->HasAnyClassFlags(CLASS_CompiledFromBlueprint)) - { - ReceiveTick(DeltaSeconds); - } + FLuaCallbackBridge::CallFloat(this, LuaModuleName, "OnTick", DeltaSeconds); } -FString ALuaDemoActor::GetModuleName_Implementation() const +void ALuaDemoActor::EndPlay(const EEndPlayReason::Type EndPlayReason) { - return LuaModuleName; + FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast(EndPlayReason)); + + Super::EndPlay(EndPlayReason); } void ALuaDemoActor::SetStatusText(const FString& InText) @@ -86,6 +86,8 @@ FString ALuaDemoActor::GetStatusTextString() const void ALuaDemoActor::SetCubeColor(FLinearColor NewColor) { + CurrentCubeColor = NewColor; + if (!CubeDynamicMaterial && CubeMesh) { CubeDynamicMaterial = CubeMesh->CreateAndSetMaterialInstanceDynamic(0); diff --git a/Source/UnrealLuaDemo/Demo/LuaDemoActor.h b/Source/UnrealLuaDemo/Demo/LuaDemoActor.h index c0287d6..3adbd08 100644 --- a/Source/UnrealLuaDemo/Demo/LuaDemoActor.h +++ b/Source/UnrealLuaDemo/Demo/LuaDemoActor.h @@ -4,7 +4,6 @@ #include "CoreMinimal.h" #include "GameFramework/Actor.h" -#include "UnLuaInterface.h" #include "LuaDemoActor.generated.h" class UStaticMeshComponent; @@ -12,11 +11,12 @@ class UTextRenderComponent; class UMaterialInstanceDynamic; /** - * Interactive demo actor driven by Lua (Script/lua/Game/LuaDemoActor.lua) - * to visually and programmatically verify UnLua binding, Tick, EventBus, and HotReload. + * C++ 薄桥接 Demo Actor:不实现 IUnLuaInterface(不在 Lua 侧继承 UE 对象), + * 通过 FLuaCallbackBridge 将 BeginPlay / Tick / EndPlay 回调分发给纯 TS 模块 Game.LuaDemoActor, + * 以便运行时 100% 通过 __MODULE__.ReimportSafely("Game.LuaDemoActor") 单文件热更旋转速度、颜色与逻辑。 */ UCLASS(Blueprintable) -class UNREALLUADEMO_API ALuaDemoActor : public AActor, public IUnLuaInterface +class UNREALLUADEMO_API ALuaDemoActor : public AActor { GENERATED_BODY() @@ -25,7 +25,7 @@ public: virtual void BeginPlay() override; virtual void Tick(float DeltaSeconds) override; - virtual FString GetModuleName_Implementation() const override; + virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; /** Updates the floating 3D status text rendered above the cube. */ UFUNCTION(BlueprintCallable, Category = "LuaDemo") @@ -39,6 +39,10 @@ public: UFUNCTION(BlueprintCallable, Category = "LuaDemo") void SetCubeColor(FLinearColor NewColor); + /** Returns the last applied dynamic material color of the demo cube. */ + UFUNCTION(BlueprintPure, Category = "LuaDemo") + FLinearColor GetCubeColor() const { return CurrentCubeColor; } + /** Returns the world location captured at BeginPlay (used for smooth bobbing). */ UFUNCTION(BlueprintPure, Category = "LuaDemo") FVector GetInitialLocation() const { return InitialLocation; } @@ -82,5 +86,6 @@ private: UPROPERTY(Transient) TObjectPtr CubeDynamicMaterial; + FLinearColor CurrentCubeColor = FLinearColor::White; FVector InitialLocation = FVector::ZeroVector; }; diff --git a/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp b/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp index 724c792..bf4c4bf 100644 --- a/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp +++ b/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp @@ -1,12 +1,17 @@ // Copyright Epic Games, Inc. All Rights Reserved. #include "HotUpdate/LuaHotUpdateSubsystem.h" +#include "Demo/LuaDemoActor.h" #include "LuaBundle/LuaBundleAsset.h" #include "LuaBundle/LuaScriptSettings.h" #include "UnrealLuaDemo.h" #include "UnLuaDelegates.h" +#include "Engine/GameInstance.h" +#include "Engine/World.h" +#include "EngineUtils.h" #include "HAL/FileManager.h" #include "Misc/CommandLine.h" +#include "Misc/DateTime.h" #include "Misc/FileHelper.h" #include "Misc/Parse.h" #include "Misc/Paths.h" @@ -17,6 +22,7 @@ namespace FCriticalSection GLuaBundleAccessMutex; TStrongObjectPtr GCachedLuaBundleAsset; bool GBundleLoadAttempted = false; + FDelegateHandle GLuaStateCreatedHandle; } void ULuaHotUpdateSubsystem::Initialize(FSubsystemCollectionBase& Collection) @@ -46,21 +52,115 @@ void ULuaHotUpdateSubsystem::Initialize(FSubsystemCollectionBase& Collection) TEXT("LuaHotUpdateSubsystem initialized [ExternalSourceMode]. OverrideDir=%s ExternalDir=%s"), *HotUpdateDir, *GetDefaultScriptDir()); } + +#if WITH_EDITOR + // PIE / Editor 模式下轮询 Saved/HotUpdate/reload.trigger,支持外部工具编译 TS 后一键触发单文件热更 + TriggerPollHandle = FTSTicker::GetCoreTicker().AddTicker( + FTickerDelegate::CreateUObject(this, &ULuaHotUpdateSubsystem::PollHotReloadTriggerFile), + 0.2f); +#endif } void ULuaHotUpdateSubsystem::Deinitialize() { +#if WITH_EDITOR + if (TriggerPollHandle.IsValid()) + { + FTSTicker::GetCoreTicker().RemoveTicker(TriggerPollHandle); + TriggerPollHandle.Reset(); + } +#endif + UE_LOG(LogUnrealLuaDemo, Log, TEXT("LuaHotUpdateSubsystem deinitialized.")); Super::Deinitialize(); } +#if WITH_EDITOR +bool ULuaHotUpdateSubsystem::PollHotReloadTriggerFile(float DeltaTime) +{ + const FString TriggerPath = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("HotUpdate/reload.trigger")); + if (!FPaths::FileExists(TriggerPath)) + { + return true; + } + + FString Content; + if (!FFileHelper::LoadFileToString(Content, *TriggerPath)) + { + return true; + } + + IFileManager::Get().Delete(*TriggerPath, false, true, true); + + TArray Lines; + Content.ParseIntoArrayLines(Lines, true); + + FString ResultLog; + for (FString Line : Lines) + { + Line.TrimStartAndEndInline(); + if (Line.IsEmpty() || Line.StartsWith(TEXT("#"))) + { + continue; + } + + bool bOk = true; + if (Line == TEXT("*")) + { + ReloadAllLuaModules(); + } + else + { + bOk = ReloadLuaModule(Line); + } + + ResultLog += FString::Printf(TEXT("[%s] target=%s ok=%s\n"), + *FDateTime::Now().ToString(), *Line, bOk ? TEXT("true") : TEXT("false")); + } + + if (UGameInstance* GI = GetGameInstance()) + { + if (UWorld* World = GI->GetWorld()) + { + for (TActorIterator It(World); It; ++It) + { + const FLinearColor C = It->GetCubeColor(); + ResultLog += FString::Printf(TEXT("Actor=%s Color=(%.2f,%.2f,%.2f) Status=%s\n"), + *It->GetName(), C.R, C.G, C.B, *It->GetStatusTextString().Replace(TEXT("\n"), TEXT(" | "))); + } + } + } + + const FString ResultPath = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("HotUpdate/reload.result")); + FFileHelper::SaveStringToFile(ResultLog, *ResultPath, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM); + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[HotReloadTrigger] Processed trigger:\n%s"), *ResultLog); + return true; +} +#endif + void ULuaHotUpdateSubsystem::RegisterHotUpdateLoader() { FUnLuaDelegates::CustomLoadLuaFile.BindStatic(&ULuaHotUpdateSubsystem::HandleCustomLoadLuaFile); + if (!GLuaStateCreatedHandle.IsValid()) + { + GLuaStateCreatedHandle = FUnLuaDelegates::OnLuaStateCreated.AddStatic(&ULuaHotUpdateSubsystem::HandleLuaStateCreated); + } + + // 若 UnLua 插件先于游戏模块启动并已创建了 FLuaEnv(如 -game / Standalone 模式),立即补初始化运行时 + for (const TPair& Pair : UnLua::FLuaEnv::GetAll()) + { + HandleLuaStateCreated(Pair.Key); + } } void ULuaHotUpdateSubsystem::UnregisterHotUpdateLoader() { + if (GLuaStateCreatedHandle.IsValid()) + { + FUnLuaDelegates::OnLuaStateCreated.Remove(GLuaStateCreatedHandle); + GLuaStateCreatedHandle.Reset(); + } + FUnLuaDelegates::CustomLoadLuaFile.Unbind(); FScopeLock Lock(&GLuaBundleAccessMutex); @@ -71,6 +171,29 @@ void ULuaHotUpdateSubsystem::UnregisterHotUpdateLoader() GBundleLoadAttempted = false; } +void ULuaHotUpdateSubsystem::HandleLuaStateCreated(lua_State* L) +{ + if (!L) + { + return; + } + + if (UnLua::FLuaEnv* Env = UnLua::FLuaEnv::FindEnv(L)) + { + const bool bOk = Env->DoString( + TEXT("if not _G.__MODULE__ then require('Lib.Module') end\nif not _G.__TS__DefineClass then require('Lib.Class') end"), + TEXT("InitTs2LuaModuleRuntime")); + if (!bOk) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[ts2lua] Failed to initialize Lib.Module / Lib.Class runtime.")); + } + else + { + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[ts2lua] Initialized Lib.Module & Lib.Class runtime.")); + } + } +} + bool ULuaHotUpdateSubsystem::ShouldUseLuaBundle() { #if WITH_EDITOR @@ -157,7 +280,7 @@ void ULuaHotUpdateSubsystem::ReloadAllLuaModules() { if (UnLua::FLuaEnv* Env = Pair.Value) { - Env->DoString(TEXT("require('Framework.HotReload').ReloadAll()"), TEXT("HotReloadAll")); + Env->DoString(TEXT("__MODULE__.Import('Framework.HotReload').ReloadAll()"), TEXT("HotReloadAll")); } } } @@ -181,7 +304,7 @@ bool ULuaHotUpdateSubsystem::ReloadLuaModule(const FString& ModuleName) EscapedName.ReplaceInline(TEXT("\\"), TEXT("\\\\")); EscapedName.ReplaceInline(TEXT("'"), TEXT("\\'")); - const FString Chunk = FString::Printf(TEXT("require('Framework.HotReload').ReloadModule('%s')"), *EscapedName); + const FString Chunk = FString::Printf(TEXT("__MODULE__.Import('Framework.HotReload').ReloadModule('%s')"), *EscapedName); bool bAnySucceeded = false; for (const TPair& Pair : AllEnvs) diff --git a/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.h b/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.h index bd934b2..057d059 100644 --- a/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.h +++ b/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.h @@ -3,6 +3,7 @@ #pragma once #include "CoreMinimal.h" +#include "Containers/Ticker.h" #include "Subsystems/GameInstanceSubsystem.h" #include "LuaEnv.h" #include "LuaHotUpdateSubsystem.generated.h" @@ -64,6 +65,12 @@ public: private: static ULuaBundleAsset* GetOrLoadLuaBundleAsset(); + static void HandleLuaStateCreated(lua_State* L); static bool HandleCustomLoadLuaFile(UnLua::FLuaEnv& Env, const FString& RelativeFilePath, TArray& Data, FString& FullFilePath); static bool TryLoadLuaFromRoot(const FString& RootDir, const FString& NormalizedModulePath, TArray& OutData, FString& OutFullPath); + +#if WITH_EDITOR + bool PollHotReloadTriggerFile(float DeltaTime); + FTSTicker::FDelegateHandle TriggerPollHandle; +#endif }; diff --git a/Source/UnrealLuaDemo/UnrealLuaDemo.cpp b/Source/UnrealLuaDemo/UnrealLuaDemo.cpp index fba8f9f..19c1f56 100644 --- a/Source/UnrealLuaDemo/UnrealLuaDemo.cpp +++ b/Source/UnrealLuaDemo/UnrealLuaDemo.cpp @@ -60,7 +60,7 @@ void FUnrealLuaDemoModule::StartupModule() UnLua::PushUObject(L, World); lua_setglobal(L, "__UE_TEST_WORLD"); } - Env->DoString(TEXT("require('Tests.UE.UERuntimeSuite').RunAllInUE(_G.__UE_TEST_WORLD)"), TEXT("Lua.RunTests")); + Env->DoString(TEXT("__MODULE__.Import('Tests.UE.UERuntimeSuite').RunAllInUE(_G.__UE_TEST_WORLD)"), TEXT("Lua.RunTests")); if (L) { lua_pushnil(L); diff --git a/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.cpp b/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.cpp index c66c3c4..9333999 100644 --- a/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.cpp +++ b/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.cpp @@ -89,8 +89,8 @@ int32 URunLuaTestsCommandlet::Main(const FString& Params) lua_setglobal(L, "__UE_TEST_TICK"); const FString RunChunk = TEXT( - "local suite = require('Tests.UE.UERuntimeSuite')\n" - "local runner = require('Tests.Harness.TestRunner')\n" + "local suite = __MODULE__.Import('Tests.UE.UERuntimeSuite')\n" + "local runner = __MODULE__.Import('Tests.Harness.TestRunner')\n" "local summary = suite.RunAllInUE(_G.__UE_TEST_WORLD)\n" "_G.__UE_TEST_TOTAL = summary.total or 0\n" "_G.__UE_TEST_PASSED = summary.passed or 0\n"