feat: upgrade to ts2lua-unreal v0.3.0 and refactor Game classes to pure C++ callback + TS composition hot-reload

This commit is contained in:
szy73711 committed 2026-11-30 02:42:51 +08:00
1 parent 4ad4a8f36f
commit 783dccf53d
64 files changed
+2368 -714

No files matched your search

+34 -6
View File
@@ -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
+23 -2
View File
@@ -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
+47 -68
View File
@@ -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
+3 -2
View File
@@ -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
+9 -8
View File
@@ -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
+237 -63
View File
@@ -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
+10 -9
View File
@@ -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
+11 -10
View File
@@ -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
+15 -14
View File
@@ -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
+53
View File
@@ -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,
}
+649
View File
@@ -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__
@@ -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
@@ -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
@@ -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)
+16 -9
View File
@@ -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
+9 -10
View File
@@ -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
@@ -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
@@ -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
+4 -5
View File
@@ -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
+56 -33
View File
@@ -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
@@ -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
+4 -5
View File
@@ -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
+5 -6
View File
@@ -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
@@ -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
+3 -2
View File
@@ -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
+38 -25
View File
@@ -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
@@ -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
@@ -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
@@ -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
+21 -12
View File
@@ -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
+118 -32
View File
@@ -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
@@ -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
@@ -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
+7 -15
View File
@@ -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
}
+3 -3
View File
@@ -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",
+1 -1
View File
@@ -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"
}
}
+4 -2
View File
@@ -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], {
+5 -1
View File
@@ -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 {
+1
View File
@@ -7,6 +7,7 @@ interface EventEntry {
owner?: unknown;
}
/** @module_data */
let Listeners: Record<string, EventEntry[] | undefined> = {};
export function On<TOwner>(
+38 -53
View File
@@ -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<string, unknown>)["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;
}
+7 -8
View File
@@ -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));
}
+207 -68
View File
@@ -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<string, DemoActorController | undefined> = {};
/** @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()
);
};
+9 -10
View File
@@ -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();
}
+15 -16
View File
@@ -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));
}
+15 -16
View File
@@ -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));
}
@@ -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>(
LuaDemoActor as unknown as Record<string, any>,
const fakeActor = CreateBoundInstance<UE.ALuaDemoActor>(
{},
"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();
});
});
+71 -3
View File
@@ -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>(
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>(
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();
});
});
}
+6
View File
@@ -14,3 +14,9 @@ interface LuaPackageTable {
declare var GameFramework: Record<string, unknown> | 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;
}
}