From 96e3f0d00949c5467d95320668c659de7c192e53 Mon Sep 17 00:00:00 2001 From: szy73711 Date: Sun, 29 Nov 2026 15:05:35 +0800 Subject: [PATCH] feat(test): add real UE 5.8 RunLuaTests commandlet, Lua.RunTests command, and fix UnLua .d.ts math/UObject bugs --- .../Private/UnLuaIntelliSenseGenerator.cpp | 2 + .../Private/UnLuaTypeScriptGenerator.cpp | 64 +-- .../Tests/Extra/LifecycleAndMemoryTest.lua | 3 +- Script/lua/Tests/Gameplay/GameplaySuite.lua | 11 +- Script/lua/Tests/Harness/MockUnLuaRuntime.lua | 45 +- Script/lua/Tests/Harness/TestRunner.lua | 26 +- Script/lua/Tests/UE/UERuntimeSuite.lua | 462 ++++++++++++++++++ Script/lua/Tests/UE/UETimerTestActor.lua | 26 + .../UnLuaExamples/Ex06_NativeContainers.lua | 2 +- .../UnLuaExamples/Ex08_StructAndTrace.lua | 25 +- .../UnLuaExamples/Ex09_AssetRefAndUMG.lua | 11 +- Script/ts/README.md | 8 +- Script/ts/package.json | 1 + .../src/Tests/Extra/LifecycleAndMemoryTest.ts | 3 +- Script/ts/src/Tests/Gameplay/GameplaySuite.ts | 12 +- .../ts/src/Tests/Harness/MockUnLuaRuntime.ts | 46 +- Script/ts/src/Tests/Harness/TestRunner.ts | 41 +- Script/ts/src/Tests/UE/UERuntimeSuite.ts | 364 ++++++++++++++ Script/ts/src/Tests/UE/UETimerTestActor.ts | 43 ++ .../UnLuaExamples/Ex06_NativeContainers.ts | 4 +- .../UnLuaExamples/Ex08_StructAndTrace.ts | 30 +- .../UnLuaExamples/Ex09_AssetRefAndUMG.ts | 13 +- Script/ts/types/project.d.ts | 2 + Script/ts/types/ue/Script/CoreUObject.d.ts | 60 ++- Source/UnrealLuaDemo/UnrealLuaDemo.cpp | 44 ++ Source/UnrealLuaDemo/UnrealLuaDemo.h | 1 + .../RunLuaTestsCommandlet.cpp | 172 +++++++ .../RunLuaTestsCommandlet.h | 26 + .../UnrealLuaDemoEditor.Build.cs | 4 +- 29 files changed, 1417 insertions(+), 134 deletions(-) create mode 100644 Script/lua/Tests/UE/UERuntimeSuite.lua create mode 100644 Script/lua/Tests/UE/UETimerTestActor.lua create mode 100644 Script/ts/src/Tests/UE/UERuntimeSuite.ts create mode 100644 Script/ts/src/Tests/UE/UETimerTestActor.ts create mode 100644 Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.cpp create mode 100644 Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.h diff --git a/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaIntelliSenseGenerator.cpp b/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaIntelliSenseGenerator.cpp index a2db0d4..eca5480 100644 --- a/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaIntelliSenseGenerator.cpp +++ b/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaIntelliSenseGenerator.cpp @@ -425,3 +425,5 @@ void FUnLuaIntelliSenseGenerator::OnAssetUpdated(const FAssetData& AssetData) Export(Blueprint); } + +#undef LOCTEXT_NAMESPACE diff --git a/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaTypeScriptGenerator.cpp b/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaTypeScriptGenerator.cpp index c596550..ddc5545 100644 --- a/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaTypeScriptGenerator.cpp +++ b/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaTypeScriptGenerator.cpp @@ -1064,7 +1064,10 @@ namespace UnLuaTypeScriptGenInternal *DataTableType)); } - AddStatic(TEXT("StaticClass"), TEXT("static StaticClass(this: void): UClass;")); + if (TypeName != TEXT("UObject") && TypeName != TEXT("UClass")) + { + AddStatic(TEXT("StaticClass"), TEXT("static StaticClass(this: void): UClass;")); + } } /** @@ -1089,14 +1092,15 @@ namespace UnLuaTypeScriptGenInternal } }; + // Note: In UnLua LuaLib_Math.h, Add/Sub/Mul/Div use bAssignment=true (mutate self in-place and return 0 values / void). if (TypeName == TEXT("FVector")) { AddMethod(TEXT("Set"), TEXT("Set(X?: number, Y?: number, Z?: number): void;")); AddMethod(TEXT("Normalize"), TEXT("Normalize(Tolerance?: number): boolean;")); - AddMethod(TEXT("Add"), TEXT("Add(other: FVector | number): FVector;")); - AddMethod(TEXT("Sub"), TEXT("Sub(other: FVector | number): FVector;")); - AddMethod(TEXT("Mul"), TEXT("Mul(other: FVector | number): FVector;")); - AddMethod(TEXT("Div"), TEXT("Div(other: FVector | number): FVector;")); + AddMethod(TEXT("Add"), TEXT("Add(other: FVector | number): void;")); + AddMethod(TEXT("Sub"), TEXT("Sub(other: FVector | number): void;")); + AddMethod(TEXT("Mul"), TEXT("Mul(other: FVector | number): void;")); + AddMethod(TEXT("Div"), TEXT("Div(other: FVector | number): void;")); PostDecls += TEXT(" function FVector(this: void): FVector;\n"); PostDecls += TEXT(" function FVector(this: void, XYZ: number): FVector;\n"); PostDecls += TEXT(" function FVector(this: void, X: number, Y: number, Z: number): FVector;\n"); @@ -1106,10 +1110,10 @@ namespace UnLuaTypeScriptGenInternal AddMethod(TEXT("Set"), TEXT("Set(X?: number, Y?: number): void;")); AddMethod(TEXT("Normalize"), TEXT("Normalize(Tolerance?: number): void;")); AddMethod(TEXT("IsNormalized"), TEXT("IsNormalized(): boolean;")); - AddMethod(TEXT("Add"), TEXT("Add(other: FVector2D | number): FVector2D;")); - AddMethod(TEXT("Sub"), TEXT("Sub(other: FVector2D | number): FVector2D;")); - AddMethod(TEXT("Mul"), TEXT("Mul(other: FVector2D | number): FVector2D;")); - AddMethod(TEXT("Div"), TEXT("Div(other: FVector2D | number): FVector2D;")); + AddMethod(TEXT("Add"), TEXT("Add(other: FVector2D | number): void;")); + AddMethod(TEXT("Sub"), TEXT("Sub(other: FVector2D | number): void;")); + AddMethod(TEXT("Mul"), TEXT("Mul(other: FVector2D | number): void;")); + AddMethod(TEXT("Div"), TEXT("Div(other: FVector2D | number): void;")); PostDecls += TEXT(" function FVector2D(this: void): FVector2D;\n"); PostDecls += TEXT(" function FVector2D(this: void, XY: number): FVector2D;\n"); PostDecls += TEXT(" function FVector2D(this: void, X: number, Y: number): FVector2D;\n"); @@ -1117,10 +1121,10 @@ namespace UnLuaTypeScriptGenInternal else if (TypeName == TEXT("FVector4")) { AddMethod(TEXT("Set"), TEXT("Set(X?: number, Y?: number, Z?: number, W?: number): void;")); - AddMethod(TEXT("Add"), TEXT("Add(other: FVector4 | number): FVector4;")); - AddMethod(TEXT("Sub"), TEXT("Sub(other: FVector4 | number): FVector4;")); - AddMethod(TEXT("Mul"), TEXT("Mul(other: FVector4 | number): FVector4;")); - AddMethod(TEXT("Div"), TEXT("Div(other: FVector4 | number): FVector4;")); + AddMethod(TEXT("Add"), TEXT("Add(other: FVector4 | number): void;")); + AddMethod(TEXT("Sub"), TEXT("Sub(other: FVector4 | number): void;")); + AddMethod(TEXT("Mul"), TEXT("Mul(other: FVector4 | number): void;")); + AddMethod(TEXT("Div"), TEXT("Div(other: FVector4 | number): void;")); PostDecls += TEXT(" function FVector4(this: void, X?: number, Y?: number, Z?: number, W?: number): FVector4;\n"); } else if (TypeName == TEXT("FRotator")) @@ -1130,9 +1134,9 @@ namespace UnLuaTypeScriptGenInternal AddMethod(TEXT("GetRightVector"), TEXT("GetRightVector(Out?: FVector): FVector;")); AddMethod(TEXT("GetUpVector"), TEXT("GetUpVector(Out?: FVector): FVector;")); AddMethod(TEXT("GetUnitAxis"), FString::Printf(TEXT("GetUnitAxis(Axis: %s, Out?: FVector): FVector;"), *AxisType)); - AddMethod(TEXT("Add"), TEXT("Add(other: FRotator): FRotator;")); - AddMethod(TEXT("Sub"), TEXT("Sub(other: FRotator): FRotator;")); - AddMethod(TEXT("Mul"), TEXT("Mul(scale: number): FRotator;")); + AddMethod(TEXT("Add"), TEXT("Add(other: FRotator): void;")); + AddMethod(TEXT("Sub"), TEXT("Sub(other: FRotator): void;")); + AddMethod(TEXT("Mul"), TEXT("Mul(scale: number): void;")); PostDecls += TEXT(" function FRotator(this: void): FRotator;\n"); PostDecls += TEXT(" function FRotator(this: void, F: number): FRotator;\n"); PostDecls += TEXT(" function FRotator(this: void, Pitch: number, Yaw: number, Roll: number): FRotator;\n"); @@ -1140,10 +1144,10 @@ namespace UnLuaTypeScriptGenInternal else if (TypeName == TEXT("FLinearColor")) { AddMethod(TEXT("Set"), TEXT("Set(R?: number, G?: number, B?: number, A?: number): void;")); - AddMethod(TEXT("Add"), TEXT("Add(other: FLinearColor): FLinearColor;")); - AddMethod(TEXT("Sub"), TEXT("Sub(other: FLinearColor): FLinearColor;")); - AddMethod(TEXT("Mul"), TEXT("Mul(other: FLinearColor | number): FLinearColor;")); - AddMethod(TEXT("Div"), TEXT("Div(other: FLinearColor | number): FLinearColor;")); + AddMethod(TEXT("Add"), TEXT("Add(other: FLinearColor): void;")); + AddMethod(TEXT("Sub"), TEXT("Sub(other: FLinearColor): void;")); + AddMethod(TEXT("Mul"), TEXT("Mul(other: FLinearColor | number): void;")); + AddMethod(TEXT("Div"), TEXT("Div(other: FLinearColor | number): void;")); PostDecls += TEXT(" function FLinearColor(this: void): FLinearColor;\n"); PostDecls += TEXT(" function FLinearColor(this: void, R: number, G: number, B: number, A?: number): FLinearColor;\n"); } @@ -1160,7 +1164,7 @@ namespace UnLuaTypeScriptGenInternal AddMethod(TEXT("Set"), TEXT("Set(X?: number, Y?: number, Z?: number, W?: number): void;")); AddMethod(TEXT("Normalize"), TEXT("Normalize(Tolerance?: number): void;")); AddMethod(TEXT("GetNormalized"), TEXT("GetNormalized(Tolerance?: number): FQuat;")); - AddMethod(TEXT("Mul"), TEXT("Mul(other: FQuat | number): FQuat;")); + AddMethod(TEXT("Mul"), TEXT("Mul(other: FQuat | number): void;")); AddStaticMethod(TEXT("FromAxisAndAngle"), TEXT("function FromAxisAndAngle(this: void, Axis: FVector, Angle: number, Out?: FQuat): FQuat;")); PostDecls += TEXT(" function FQuat(this: void): FQuat;\n"); PostDecls += TEXT(" function FQuat(this: void, X: number, Y: number, Z: number, W: number): FQuat;\n"); @@ -1169,16 +1173,16 @@ namespace UnLuaTypeScriptGenInternal { AddMethod(TEXT("Blend"), TEXT("Blend(B: FTransform, C: FTransform, Alpha: number): void;")); AddMethod(TEXT("BlendWith"), TEXT("BlendWith(B: FTransform, Alpha: number): void;")); - AddMethod(TEXT("Mul"), TEXT("Mul(other: FTransform | number): FTransform;")); + AddMethod(TEXT("Mul"), TEXT("Mul(other: FTransform | number): void;")); PostDecls += TEXT(" function FTransform(this: void, Rotation?: FQuat, Translation?: FVector, Scale3D?: FVector): FTransform;\n"); } else if (TypeName == TEXT("FIntPoint")) { AddMethod(TEXT("Set"), TEXT("Set(X?: number, Y?: number): void;")); - AddMethod(TEXT("Add"), TEXT("Add(other: FIntPoint | number): FIntPoint;")); - AddMethod(TEXT("Sub"), TEXT("Sub(other: FIntPoint | number): FIntPoint;")); - AddMethod(TEXT("Mul"), TEXT("Mul(other: FIntPoint | number): FIntPoint;")); - AddMethod(TEXT("Div"), TEXT("Div(other: FIntPoint | number): FIntPoint;")); + AddMethod(TEXT("Add"), TEXT("Add(other: FIntPoint | number): void;")); + AddMethod(TEXT("Sub"), TEXT("Sub(other: FIntPoint | number): void;")); + AddMethod(TEXT("Mul"), TEXT("Mul(other: FIntPoint | number): void;")); + AddMethod(TEXT("Div"), TEXT("Div(other: FIntPoint | number): void;")); PostDecls += TEXT(" function FIntPoint(this: void): FIntPoint;\n"); PostDecls += TEXT(" function FIntPoint(this: void, XY: number): FIntPoint;\n"); PostDecls += TEXT(" function FIntPoint(this: void, X: number, Y: number): FIntPoint;\n"); @@ -1187,10 +1191,10 @@ namespace UnLuaTypeScriptGenInternal { AddMethod(TEXT("Set"), TEXT("Set(X?: number, Y?: number, Z?: number): void;")); AddMethod(TEXT("SizeSquared"), TEXT("SizeSquared(): number;")); - AddMethod(TEXT("Add"), TEXT("Add(other: FIntVector | number): FIntVector;")); - AddMethod(TEXT("Sub"), TEXT("Sub(other: FIntVector | number): FIntVector;")); - AddMethod(TEXT("Mul"), TEXT("Mul(other: FIntVector | number): FIntVector;")); - AddMethod(TEXT("Div"), TEXT("Div(other: FIntVector | number): FIntVector;")); + AddMethod(TEXT("Add"), TEXT("Add(other: FIntVector | number): void;")); + AddMethod(TEXT("Sub"), TEXT("Sub(other: FIntVector | number): void;")); + AddMethod(TEXT("Mul"), TEXT("Mul(other: FIntVector | number): void;")); + AddMethod(TEXT("Div"), TEXT("Div(other: FIntVector | number): void;")); PostDecls += TEXT(" function FIntVector(this: void): FIntVector;\n"); PostDecls += TEXT(" function FIntVector(this: void, XYZ: number): FIntVector;\n"); PostDecls += TEXT(" function FIntVector(this: void, X: number, Y: number, Z: number): FIntVector;\n"); diff --git a/Script/lua/Tests/Extra/LifecycleAndMemoryTest.lua b/Script/lua/Tests/Extra/LifecycleAndMemoryTest.lua index e3f7ad2..32f4ed6 100644 --- a/Script/lua/Tests/Extra/LifecycleAndMemoryTest.lua +++ b/Script/lua/Tests/Extra/LifecycleAndMemoryTest.lua @@ -50,8 +50,7 @@ function ____exports.RunLifecycleAndMemoryTests() EventBus.Clear() local actor = CreateBoundInstance(LifecycleSafetyActor, "AActor") local asset = UE.UObject.Load("/Game/Data/DA_Config.DA_Config") - local weak = UE.FWeakObjectPtr() - weak:Set(actor) + local weak = UE.FWeakObjectPtr(actor) actor:ReceiveBeginPlay() actor:HoldManualRef(asset) AssertEqual( diff --git a/Script/lua/Tests/Gameplay/GameplaySuite.lua b/Script/lua/Tests/Gameplay/GameplaySuite.lua index 88404a7..c07aa5d 100644 --- a/Script/lua/Tests/Gameplay/GameplaySuite.lua +++ b/Script/lua/Tests/Gameplay/GameplaySuite.lua @@ -382,7 +382,16 @@ function ____exports.RunGameplayTests() runner:GetActiveTaskCount(), 0 ) - local ownerActor = CreateBoundInstance({}, "AActor") + local world = _G.__UE_TEST_WORLD + local ownerActor = world ~= nil and world:SpawnActor( + UE.AActor.StaticClass(), + UE.FTransform( + UE.FRotator(0, 0, 0):ToQuat(), + UE.FVector(0, 0, 0), + UE.FVector(1, 1, 1) + ), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn + ) or CreateBoundInstance({}, "AActor") local postDestroyExecuted = false runner:Start( function() diff --git a/Script/lua/Tests/Harness/MockUnLuaRuntime.lua b/Script/lua/Tests/Harness/MockUnLuaRuntime.lua index c6e021f..1980a46 100644 --- a/Script/lua/Tests/Harness/MockUnLuaRuntime.lua +++ b/Script/lua/Tests/Harness/MockUnLuaRuntime.lua @@ -281,7 +281,7 @@ local function CreateMockTArray() local i = 0 while i < #data do if data[i + 1] == item then - return 0 + return i + 1 end i = i + 1 end @@ -566,27 +566,47 @@ local function CreateMockFVector(x, y, z) end, Add = function(self, other) if type(other) == "number" then - return CreateMockFVector(self.X + other, self.Y + other, self.Z + other) + self.X = self.X + other + self.Y = self.Y + other + self.Z = self.Z + other + else + self.X = self.X + other.X + self.Y = self.Y + other.Y + self.Z = self.Z + other.Z end - return CreateMockFVector(self.X + other.X, self.Y + other.Y, self.Z + other.Z) end, Sub = function(self, other) if type(other) == "number" then - return CreateMockFVector(self.X - other, self.Y - other, self.Z - other) + self.X = self.X - other + self.Y = self.Y - other + self.Z = self.Z - other + else + self.X = self.X - other.X + self.Y = self.Y - other.Y + self.Z = self.Z - other.Z end - return CreateMockFVector(self.X - other.X, self.Y - other.Y, self.Z - other.Z) end, Mul = function(self, other) if type(other) == "number" then - return CreateMockFVector(self.X * other, self.Y * other, self.Z * other) + self.X = self.X * other + self.Y = self.Y * other + self.Z = self.Z * other + else + self.X = self.X * other.X + self.Y = self.Y * other.Y + self.Z = self.Z * other.Z end - return CreateMockFVector(self.X * other.X, self.Y * other.Y, self.Z * other.Z) end, Div = function(self, other) if type(other) == "number" then - return CreateMockFVector(self.X / other, self.Y / other, self.Z / other) + self.X = self.X / other + self.Y = self.Y / other + self.Z = self.Z / other + else + self.X = self.X / other.X + self.Y = self.Y / other.Y + self.Z = self.Z / other.Z end - return CreateMockFVector(self.X / other.X, self.Y / other.Y, self.Z / other.Z) end, Dot = function(self, other) return self.X * other.X + self.Y * other.Y + self.Z * other.Z @@ -880,8 +900,8 @@ function ____exports.InstallIfNeeded() Normal = CreateMockFVector(0, 0, 1) } end, FActorSpawnParameters = function() return {Name = "", bNoFail = false, SpawnCollisionHandlingOverride = 0} end, - FWeakObjectPtr = function() - local refObj = nil + FWeakObjectPtr = function(initialObj) + local refObj = initialObj return { Set = function(self, o) refObj = o @@ -1050,6 +1070,9 @@ function ____exports.InstallIfNeeded() hit.Distance = dist * 0.5 hit.Location = CreateMockFVector((startVec.X + endVec.X) * 0.5, (startVec.Y + endVec.Y) * 0.5, (startVec.Z + endVec.Z) * 0.5) hit.ImpactPoint = hit.Location + if outHit ~= nil then + return bHit, nil + end return bHit, hit end } diff --git a/Script/lua/Tests/Harness/TestRunner.lua b/Script/lua/Tests/Harness/TestRunner.lua index b405f63..93607f4 100644 --- a/Script/lua/Tests/Harness/TestRunner.lua +++ b/Script/lua/Tests/Harness/TestRunner.lua @@ -127,26 +127,36 @@ function ____exports.GetSummary() end return {total = #results, passed = passed, failed = failed, results = results} end -function ____exports.PrintReport() - local summary = ____exports.GetSummary() +function ____exports.FormatReport(summary) + local s = summary or ____exports.GetSummary() + local lines = {} local lastSuite = "" do local i = 0 - while i < #summary.results do - local r = summary.results[i + 1] + while i < #s.results do + local r = s.results[i + 1] if r.suite ~= lastSuite then lastSuite = r.suite - print(string.format("\n[%s]", r.suite)) + lines[#lines + 1] = "" + lines[#lines + 1] = string.format("[%s]", r.suite) end if r.passed then - print(string.format(" PASS %s", r.name)) + lines[#lines + 1] = string.format(" PASS %s", r.name) else - print(string.format(" FAIL %s\n -> %s", r.name, r.errorMessage or "unknown error")) + lines[#lines + 1] = string.format(" FAIL %s\n -> %s", r.name, r.errorMessage or "unknown error") end i = i + 1 end end - print(string.format("\n========================================\nTotal: %d | Passed: %d | Failed: %d\n========================================", summary.total, summary.passed, summary.failed)) + lines[#lines + 1] = "" + lines[#lines + 1] = "========================================" + lines[#lines + 1] = string.format("Total: %d | Passed: %d | Failed: %d", s.total, s.passed, s.failed) + lines[#lines + 1] = "========================================" + return table.concat(lines, "\n") +end +function ____exports.PrintReport() + local summary = ____exports.GetSummary() + print(____exports.FormatReport(summary)) return summary end return ____exports diff --git a/Script/lua/Tests/UE/UERuntimeSuite.lua b/Script/lua/Tests/UE/UERuntimeSuite.lua new file mode 100644 index 0000000..72af6f4 --- /dev/null +++ b/Script/lua/Tests/UE/UERuntimeSuite.lua @@ -0,0 +1,462 @@ +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 UnLuaBaseActorClass = require("Tests.Syntax.UnLuaBaseActor") +local function TickUEWorld(steps, deltaSeconds) + local tickFn = _G.__UE_TEST_TICK + if tickFn == nil then + return + end + do + local i = 0 + while i < steps do + tickFn(deltaSeconds) + i = i + 1 + end + end +end +function ____exports.RunUERuntimeSuite(world) + local canTickWorld = _G.__UE_TEST_TICK ~= nil + Suite( + "UE.RealEngineIntegration", + function() + Test( + "Real UE C++ TArray / TMap / TSet containers & native __pairs iteration", + function() + VerifyTArrayOperations() + VerifyTMapOperations() + VerifyTSetOperations() + end + ) + Test( + "Real UE SpawnActor + @unlua UnLuaBaseActor (Overridden, static methods, destructuring)", + function() + local actor = world:SpawnActor( + UE.ATargetPoint.StaticClass(), + UE.FTransform( + UE.FRotator(0, 0, 0):ToQuat(), + UE.FVector(0, 0, 0), + UE.FVector(1, 1, 1) + ), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + nil, + nil, + "Tests.Syntax.UnLuaBaseActor" + ) + AssertNotNil(actor) + AssertTrue(UE.UKismetSystemLibrary.IsValid(actor)) + AssertTrue(actor:IsA(UE.AActor.StaticClass())) + AssertEqual( + actor:GetHp(), + 100 + ) + AssertArrayEqual( + actor:GetTrace(), + {"Base.ReceiveBeginPlay"} + ) + AssertEqual( + actor:ApplyConfig({name = "UEHero"}), + "UEHero:100" + ) + AssertEqual( + actor:ApplyConfig({name = "UEBoss", hp = 888}), + "UEBoss:888" + ) + AssertEqual( + actor:SumScores({10}), + 15 + ) + AssertEqual( + actor:SumScores({1, 2, 3, 4}), + 10 + ) + AssertEqual( + UnLuaBaseActorClass:StaticWithSelf(25), + 125 + ) + AssertEqual( + UnLuaBaseActorClass.StaticNoSelf(7, 8), + 15 + ) + AssertEqual( + UnLuaBaseActorClass.StaticDocNoSelf(9), + 27 + ) + actor:K2_DestroyActor() + end + ) + Test( + "Real UE SpawnActor + 3-level @unlua inheritance (GrandChild -> Sub -> Base -> AActor)", + function() + local grand = world:SpawnActor( + UE.ATriggerBox.StaticClass(), + UE.FTransform( + UE.FRotator(0, 0, 0):ToQuat(), + UE.FVector(0, 0, 0), + UE.FVector(1, 1, 1) + ), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + nil, + nil, + "Tests.Syntax.UnLuaGrandChildActor" + ) + AssertNotNil(grand) + AssertArrayEqual( + grand:GetTrace(), + {"Base.ReceiveBeginPlay", "Sub.ReceiveBeginPlay", "GrandChild.ReceiveBeginPlay"} + ) + AssertEqual( + grand:GetFaction(), + "Ally" + ) + AssertEqual( + grand:GetTier(), + 3 + ) + AssertEqual( + grand:ComputeBonus(10), + 33 + ) + AssertEqual( + grand:SetupWithFaction({name = "Knight", hp = 250}, "Enemy"), + "Knight:250[Enemy]" + ) + grand:K2_DestroyActor() + end + ) + Test( + "Real UE Ex01_HelloWorld & Ex02_OverrideBlueprintEvents lifecycle", + function() + local hello = world:SpawnActor( + UE.ATriggerSphere.StaticClass(), + UE.FTransform( + UE.FRotator(0, 0, 0):ToQuat(), + UE.FVector(0, 0, 0), + UE.FVector(1, 1, 1) + ), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + nil, + nil, + "Tests.UnLuaExamples.Ex01_HelloWorld" + ) + AssertNotNil(hello) + AssertTrue((string.find( + hello:GetGreeting(), + "Hello UnLua from TypeScript", + 1, + true + )) ~= nil) + hello:K2_DestroyActor() + local eventsActor = world:SpawnActor( + UE.ATriggerCapsule.StaticClass(), + UE.FTransform( + UE.FRotator(0, 0, 0):ToQuat(), + UE.FVector(0, 0, 0), + UE.FVector(1, 1, 1) + ), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + nil, + nil, + "Tests.UnLuaExamples.Ex02_OverrideBlueprintEvents" + ) + AssertNotNil(eventsActor) + local events = eventsActor:GetEvents() + AssertTrue(#events >= 2) + AssertEqual(events[1], "Initialize") + eventsActor:K2_DestroyActor() + end + ) + Test( + "Real UE Ex04 DynamicBinding: SpawnActor, SpawnActorEx & UE.NewObject with Initializer", + function() + local spawned = world:SpawnActor( + UE.APlayerStart.StaticClass(), + UE.FTransform( + UE.FRotator(0, 90, 0):ToQuat(), + UE.FVector(100, 200, 300), + UE.FVector(1, 1, 1) + ), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + nil, + nil, + "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", + {InitTag = "RealUESpawn", InitPower = 555} + ) + AssertNotNil(spawned) + AssertEqual( + spawned:GetInitTag(), + "RealUESpawn" + ) + AssertEqual( + spawned:GetInitPower(), + 555 + ) + AssertTrue(spawned:IsBeginPlayCalled()) + spawned:K2_DestroyActor() + local params = UE.FActorSpawnParameters() + params.bNoFail = true + params.SpawnCollisionHandlingOverride = UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn + local spawnedEx = world:SpawnActorEx( + UE.APlayerStart.StaticClass(), + UE.FTransform( + UE.FRotator(0, 0, 0):ToQuat(), + UE.FVector(10, 20, 30), + UE.FVector(1, 1, 1) + ), + {InitTag = "RealUESpawnEx", InitPower = 777}, + "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", + params + ) + AssertNotNil(spawnedEx) + AssertEqual( + spawnedEx:GetInitTag(), + "RealUESpawnEx" + ) + AssertEqual( + spawnedEx:GetInitPower(), + 777 + ) + spawnedEx:K2_DestroyActor() + local dynObj = UE.NewObject( + UE.ULuaBundleAsset.StaticClass(), + world, + "RealUEDynObj", + "Tests.UnLuaExamples.Ex04_DynamicObject", + {Seed = 10} + ) + AssertNotNil(dynObj) + AssertEqual( + dynObj:GetSeed(), + 10 + ) + AssertEqual( + dynObj:NextValue(), + 21 + ) + AssertEqual( + dynObj:NextValue(), + 43 + ) + end + ) + Test( + "Real UE Ex08 Struct math, K2_SetActorLocation & LineTraceSingle multi-return", + function() + local actor = world:SpawnActor( + UE.ATextRenderActor.StaticClass(), + UE.FTransform( + UE.FRotator(0, 0, 0):ToQuat(), + UE.FVector(0, 0, 0), + UE.FVector(1, 1, 1) + ), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + nil, + nil, + "Tests.UnLuaExamples.Ex08_StructAndTrace" + ) + AssertNotNil(actor) + local size, dot, dist = actor:ComputeVectorMath() + AssertNear(size, 13, 0.001) + AssertNear(dot, 0, 0.001) + AssertNear(dist, 13, 0.001) + local bHit, hitDist, impact = actor:TraceForward(500) + AssertFalse(bHit) + AssertEqual( + type(hitDist), + "number" + ) + AssertNotNil(impact) + local bHit2, outHit2 = actor:TraceForwardMultiReturn(500) + AssertFalse(bHit2) + AssertNotNil(outHit2) + actor:K2_DestroyActor() + end + ) + Test( + "Real UE UnLua.Ref / UnLua.Unref & FWeakObjectPtr validity", + function() + local obj = UE.NewObject( + UE.UObjectLibrary.StaticClass(), + world, + "WeakRefTarget" + ) + AssertTrue(UE.UKismetSystemLibrary.IsValid(obj)) + local refProxy = UnLua.Ref(obj) + AssertNotNil(refProxy) + local weak = UE.FWeakObjectPtr(obj) + AssertTrue(weak:IsValid()) + AssertNotNil(weak:Get()) + weak:Reset() + AssertFalse(weak:IsValid()) + AssertNil(weak:Get()) + UnLua.Unref(obj) + end + ) + Test( + "Real UE ALuaDemoActor (IUnLuaInterface static binding) + EventBus + Tick + EndPlay", + function() + EventBus.Clear() + local demoActor = world:SpawnActor( + UE.ALuaDemoActor.StaticClass(), + UE.FTransform( + UE.FRotator(0, 0, 0):ToQuat(), + UE.FVector(0, 0, 100), + UE.FVector(1, 1, 1) + ), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn + ) + 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, "Pings: 0", 1, true)) ~= nil) + if canTickWorld then + TickUEWorld(5, 0.05) + end + EventBus.Emit("Demo.Ping", "UERealEngineTest") + local pingedText = demoActor:GetStatusTextString() + AssertTrue((string.find(pingedText, "Pings: 1", 1, true)) ~= nil) + AssertTrue((string.find(pingedText, "Color: Gold", 1, true)) ~= nil) + local bMoved = demoActor:K2_SetActorLocation( + UE.FVector(120, 240, 360), + false, + nil, + true + ) + AssertTrue(bMoved) + local loc = demoActor:K2_GetActorLocation() + AssertNear(loc.X, 120, 0.01) + AssertNear(loc.Y, 240, 0.01) + AssertNear(loc.Z, 360, 0.01) + demoActor:K2_DestroyActor() + EventBus.Clear() + end + ) + if canTickWorld then + Test( + "Real UE FTimerManager + K2_SetTimerDelegate(UnLua.Delegate) ticked by UWorld", + function() + local timerActor = world:SpawnActor( + UE.ACameraActor.StaticClass(), + UE.FTransform( + UE.FRotator(0, 0, 0):ToQuat(), + UE.FVector(0, 0, 0), + UE.FVector(1, 1, 1) + ), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + nil, + nil, + "Tests.UE.UETimerTestActor" + ) + AssertNotNil(timerActor) + AssertTrue(timerActor:IsTimerActive()) + AssertEqual( + timerActor:GetTimerCount(), + 0 + ) + TickUEWorld(10, 0.05) + AssertTrue(timerActor:GetTimerCount() >= 3) + local countBeforeStop = timerActor:GetTimerCount() + timerActor:StopTimer() + AssertFalse(timerActor:IsTimerActive()) + TickUEWorld(6, 0.05) + AssertEqual( + timerActor:GetTimerCount(), + countBeforeStop + ) + timerActor:K2_DestroyActor() + end + ) + Test( + "Real UE FLatentActionManager + UKismetSystemLibrary.Delay coroutine (Ex07)", + function() + local latentActor = world:SpawnActor( + UE.ADecalActor.StaticClass(), + UE.FTransform( + UE.FRotator(0, 0, 0):ToQuat(), + UE.FVector(0, 0, 0), + UE.FVector(1, 1, 1) + ), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + nil, + nil, + "Tests.UnLuaExamples.Ex07_CallLatentFunction" + ) + AssertNotNil(latentActor) + AssertArrayEqual( + latentActor:GetSteps(), + {"Step1:Start"} + ) + AssertFalse(latentActor:IsCompleted()) + TickUEWorld(6, 0.1) + AssertArrayEqual( + latentActor:GetSteps(), + {"Step1:Start", "Step2:After0.5s"} + ) + AssertFalse(latentActor:IsCompleted()) + TickUEWorld(11, 0.1) + AssertArrayEqual( + latentActor:GetSteps(), + {"Step1:Start", "Step2:After0.5s", "Step3:Done"} + ) + AssertTrue(latentActor:IsCompleted()) + latentActor:K2_DestroyActor() + end + ) + end + Test( + "Real UE HotReload.ReloadModule validates arguments and emits events", + function() + EventBus.Clear() + local badOk = HotReload.ReloadModule("") + AssertFalse(badOk) + local ok = HotReload.ReloadModule("Framework.Log") + AssertTrue(ok) + EventBus.Clear() + end + ) + end + ) +end +--- 在真实 UE 5.8 + UnLua 2.3.6 环境下运行的统一入口。 +-- 可由 RunLuaTestsCommandlet 或编辑器控制台命令 `Lua.RunTests` 调用。 +function ____exports.RunAllInUE(world) + local targetWorld = world or _G.__UE_TEST_WORLD + Reset() + RunBasicTypesAndControlFlowTests() + RunFunctionsClosuresAndTuplesTests() + RunPureClassesAndGenericsTests() + RunGameplayTests() + RunLua54PitfallsTests() + if targetWorld ~= nil then + ____exports.RunUERuntimeSuite(targetWorld) + end + return PrintReport() +end +return ____exports diff --git a/Script/lua/Tests/UE/UETimerTestActor.lua b/Script/lua/Tests/UE/UETimerTestActor.lua new file mode 100644 index 0000000..d3b03fe --- /dev/null +++ b/Script/lua/Tests/UE/UETimerTestActor.lua @@ -0,0 +1,26 @@ +local UETimerTestActor = UnLua.Class() +function UETimerTestActor.ReceiveBeginPlay(self) + self.Overridden.ReceiveBeginPlay(self) + self.timerCount = 0 + self.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate({self, self.OnTimerTick}, 0.1, true) +end +function UETimerTestActor.OnTimerTick(self) + if not UE.UKismetSystemLibrary.IsValid(self) then + return + end + self.timerCount = self.timerCount + 1 +end +function UETimerTestActor.StopTimer(self) + UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(self, self.timerHandle) +end +function UETimerTestActor.GetTimerCount(self) + return self.timerCount +end +function UETimerTestActor.IsTimerActive(self) + return UE.UKismetSystemLibrary.K2_IsTimerActiveHandle(self, self.timerHandle) +end +function UETimerTestActor.ReceiveEndPlay(self, EndPlayReason) + self:StopTimer() + self.Overridden.ReceiveEndPlay(self, EndPlayReason) +end +return UETimerTestActor diff --git a/Script/lua/Tests/UnLuaExamples/Ex06_NativeContainers.lua b/Script/lua/Tests/UnLuaExamples/Ex06_NativeContainers.lua index 0fa8207..057c8d2 100644 --- a/Script/lua/Tests/UnLuaExamples/Ex06_NativeContainers.lua +++ b/Script/lua/Tests/UnLuaExamples/Ex06_NativeContainers.lua @@ -63,7 +63,7 @@ function ____exports.VerifyTArrayOperations() AssertFalse(arr:Contains(999)) AssertEqual( arr:AddUnique(25), - 0 + 2 ) AssertEqual( arr:AddUnique(40), diff --git a/Script/lua/Tests/UnLuaExamples/Ex08_StructAndTrace.lua b/Script/lua/Tests/UnLuaExamples/Ex08_StructAndTrace.lua index 0ac3e07..301c281 100644 --- a/Script/lua/Tests/UnLuaExamples/Ex08_StructAndTrace.lua +++ b/Script/lua/Tests/UnLuaExamples/Ex08_StructAndTrace.lua @@ -10,19 +10,19 @@ end function Ex08_StructAndTrace.ComputeVectorMath(self) local a = UE.FVector(3, 4, 0) local b = UE.FVector(0, 0, 12) - local c = a:Add(b) local dot = a:Dot(b) + a:Add(b) local dist = UE.FVector.Dist( UE.FVector(0, 0, 0), - c + a ) - return c:Size(), dot, dist + return a:Size(), dot, dist end function Ex08_StructAndTrace.TraceForward(self, distance) local origin = self:K2_GetActorLocation() self._tmpStart:Set(origin.X, origin.Y, origin.Z) self._tmpEnd:Set(origin.X + distance, origin.Y, origin.Z) - local bHit, hit = UE.UKismetSystemLibrary.LineTraceSingle( + local bHit, returnedHit = UE.UKismetSystemLibrary.LineTraceSingle( self, self._tmpStart, self._tmpEnd, @@ -33,8 +33,25 @@ function Ex08_StructAndTrace.TraceForward(self, distance) self._tmpHit, true ) + local hit = returnedHit or self._tmpHit return bHit, hit.Distance, hit.ImpactPoint end +function Ex08_StructAndTrace.TraceForwardMultiReturn(self, distance) + local origin = self:K2_GetActorLocation() + self._tmpStart:Set(origin.X, origin.Y, origin.Z) + self._tmpEnd:Set(origin.X + distance, origin.Y, origin.Z) + return UE.UKismetSystemLibrary.LineTraceSingle( + self, + self._tmpStart, + self._tmpEnd, + UE.ETraceTypeQuery.TraceTypeQuery1, + false, + self._ignoreActors, + UE.EDrawDebugTrace.None, + nil, + true + ) +end function Ex08_StructAndTrace.TeleportTo(self, x, y, z) local target = UE.FVector(x, y, z) local bMoved = self:K2_SetActorLocation(target, false, self._tmpHit, true) diff --git a/Script/lua/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.lua b/Script/lua/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.lua index f651e2a..dc0ef78 100644 --- a/Script/lua/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.lua +++ b/Script/lua/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.lua @@ -2,14 +2,14 @@ local Ex09_AssetRefAndUMG = UnLua.Class() function Ex09_AssetRefAndUMG.Initialize(self, _Initializer) self.isConstructed = false self.isDestructed = false - self.weakRef = UE.FWeakObjectPtr() + self.weakRef = nil end function Ex09_AssetRefAndUMG.Construct(self) self.isConstructed = true self.loadedAsset = UE.UObject.Load("/Game/UI/Textures/T_Icon.T_Icon") if self.loadedAsset ~= nil then self.refProxy = UnLua.Ref(self.loadedAsset) - self.weakRef:Set(self.loadedAsset) + self.weakRef = UE.FWeakObjectPtr(self.loadedAsset) end end function Ex09_AssetRefAndUMG.ShowOnScreen(self) @@ -30,10 +30,13 @@ function Ex09_AssetRefAndUMG.Destruct(self) self.refProxy = nil self.loadedAsset = nil end - self.weakRef:Reset() + if self.weakRef ~= nil then + self.weakRef:Reset() + self.weakRef = nil + end end function Ex09_AssetRefAndUMG.HasValidWeakAsset(self) - return self.weakRef:IsValid() + return self.weakRef ~= nil and self.weakRef:IsValid() end function Ex09_AssetRefAndUMG.IsConstructed(self) return self.isConstructed diff --git a/Script/ts/README.md b/Script/ts/README.md index e4688df..7987a6e 100644 --- a/Script/ts/README.md +++ b/Script/ts/README.md @@ -30,6 +30,7 @@ Script/ts/ ├── UnLuaExamples/ # 参考 UnLua 官方示例 01~09 的 TS 移植与验证 ├── Gameplay/ # 常用游戏系统实现(FSM/对象池/定时器/Buff属性/背包/协程/行为树) ├── Extra/ # 框架集成、热重载、Lua 5.4 陷阱与生命周期安全测试 + ├── UE/ # 真实 UE 5.8 + UnLua 2.3.6 引擎集成测试套件(UERuntimeSuite) └── RunAllTests.ts # 统一测试入口(支持 lua5.4 独立运行或在 UE 内调用) ``` @@ -44,9 +45,12 @@ npm install # 全量编译到 ../lua npm run build -# 编译并在本机 Lua 5.4 下运行全部自动化测试 +# 编译并在本机 Lua 5.4 下运行全部自动化测试(~3s) npm test +# 编译并在真实 UE 5.8 + UnLua 2.3.6 引擎内无头运行全量测试(-run=RunLuaTests) +npm run test:ue + # 增量监听模式(开发期配合 PIE + UnLua HotReload 使用) npm run watch @@ -54,6 +58,8 @@ npm run watch npm run info ``` +> 在 UE 编辑器 PIE 运行期间,也可以直接打开控制台输入 `Lua.RunTests` 在当前 PIE `UWorld` 中运行全量测试。 + ## 规范与文档 - 项目编码约束:[AGENTS.md](../../AGENTS.md) diff --git a/Script/ts/package.json b/Script/ts/package.json index d2b3d14..4e665f1 100644 --- a/Script/ts/package.json +++ b/Script/ts/package.json @@ -7,6 +7,7 @@ "build": "ts2lua-unreal build", "watch": "ts2lua-unreal watch", "test": "npm run build && node scripts/run-tests.mjs", + "test:ue": "npm run build && /Applications/Unreal5/UE_5.8/Engine/Binaries/Mac/UnrealEditor-Cmd \"$(pwd)/../../UnrealLuaDemo.uproject\" -run=RunLuaTests -unattended -nop4 -nosplash -NullRHI", "info": "ts2lua-unreal info" }, "devDependencies": { diff --git a/Script/ts/src/Tests/Extra/LifecycleAndMemoryTest.ts b/Script/ts/src/Tests/Extra/LifecycleAndMemoryTest.ts index 1656d9f..06c132f 100644 --- a/Script/ts/src/Tests/Extra/LifecycleAndMemoryTest.ts +++ b/Script/ts/src/Tests/Extra/LifecycleAndMemoryTest.ts @@ -51,8 +51,7 @@ export function RunLifecycleAndMemoryTests(): void { "AActor" ); const asset = UE.UObject.Load("/Game/Data/DA_Config.DA_Config")!; - const weak = UE.FWeakObjectPtr(); - weak.Set(actor); + const weak = UE.FWeakObjectPtr(actor); actor.ReceiveBeginPlay(); actor.HoldManualRef(asset); diff --git a/Script/ts/src/Tests/Gameplay/GameplaySuite.ts b/Script/ts/src/Tests/Gameplay/GameplaySuite.ts index 5a7a41a..ab4c369 100644 --- a/Script/ts/src/Tests/Gameplay/GameplaySuite.ts +++ b/Script/ts/src/Tests/Gameplay/GameplaySuite.ts @@ -287,8 +287,16 @@ export function RunGameplayTests(): void { AssertArrayEqual(trace, ["start", "after_delay", "entered_room"]); AssertEqual(runner.GetActiveTaskCount(), 0); - // 绑定 UObject 存活自动取消测试 - const ownerActor = CreateBoundInstance({}, "AActor"); + // 绑定 UObject 存活自动取消测试(兼容独立 Mock 环境与真实 UE 环境) + const world = _G.__UE_TEST_WORLD; + const ownerActor = + world !== undefined + ? world.SpawnActor( + UE.AActor.StaticClass(), + UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn + )! + : CreateBoundInstance({}, "AActor"); let postDestroyExecuted = false; runner.Start(() => { CoroutineTaskRunner.WaitSeconds(1.0); diff --git a/Script/ts/src/Tests/Harness/MockUnLuaRuntime.ts b/Script/ts/src/Tests/Harness/MockUnLuaRuntime.ts index 5db123c..1a27ab2 100644 --- a/Script/ts/src/Tests/Harness/MockUnLuaRuntime.ts +++ b/Script/ts/src/Tests/Harness/MockUnLuaRuntime.ts @@ -301,7 +301,7 @@ function CreateMockTArray(): UE.TArray { }, AddUnique(this: unknown, item: any) { for (let i = 0; i < data.length; i++) { - if (data[i] === item) return 0; // INDEX_NONE + 1 in UnLua = 0 + if (data[i] === item) return i + 1; // UnLua C++ 返回已有元素的 1-based 索引 } data[data.length] = item; return data.length; @@ -524,27 +524,47 @@ function CreateMockFVector(x?: number, y?: number, z?: number): UE.FVector { }, Add(this: Record, other: any) { if (type(other) === "number") { - return CreateMockFVector(this.X + other, this.Y + other, this.Z + other); + this.X += other; + this.Y += other; + this.Z += other; + } else { + this.X += other.X; + this.Y += other.Y; + this.Z += other.Z; } - return CreateMockFVector(this.X + other.X, this.Y + other.Y, this.Z + other.Z); }, Sub(this: Record, other: any) { if (type(other) === "number") { - return CreateMockFVector(this.X - other, this.Y - other, this.Z - other); + this.X -= other; + this.Y -= other; + this.Z -= other; + } else { + this.X -= other.X; + this.Y -= other.Y; + this.Z -= other.Z; } - return CreateMockFVector(this.X - other.X, this.Y - other.Y, this.Z - other.Z); }, Mul(this: Record, other: any) { if (type(other) === "number") { - return CreateMockFVector(this.X * other, this.Y * other, this.Z * other); + this.X *= other; + this.Y *= other; + this.Z *= other; + } else { + this.X *= other.X; + this.Y *= other.Y; + this.Z *= other.Z; } - return CreateMockFVector(this.X * other.X, this.Y * other.Y, this.Z * other.Z); }, Div(this: Record, other: any) { if (type(other) === "number") { - return CreateMockFVector(this.X / other, this.Y / other, this.Z / other); + this.X /= other; + this.Y /= other; + this.Z /= other; + } else { + this.X /= other.X; + this.Y /= other.Y; + this.Z /= other.Z; } - return CreateMockFVector(this.X / other.X, this.Y / other.Y, this.Z / other.Z); }, Dot(this: Record, other: any) { return this.X * other.X + this.Y * other.Y + this.Z * other.Z; @@ -846,8 +866,8 @@ export function InstallIfNeeded(): void { bNoFail: false, SpawnCollisionHandlingOverride: 0, }), - FWeakObjectPtr: () => { - let refObj: Record | undefined = undefined; + FWeakObjectPtr: (initialObj?: Record) => { + let refObj: Record | undefined = initialObj; return { Set(this: unknown, o: Record | undefined) { refObj = o; @@ -1046,6 +1066,10 @@ export function InstallIfNeeded(): void { (startVec.Z + endVec.Z) * 0.5 ); hit.ImpactPoint = hit.Location; + // 还原 UnLua 真实语义:传入复用 Out 参数时原地修改并返回单值;传入 nil 时返回多值 (bHit, newHit) + if (outHit !== undefined) { + return $multi(bHit, undefined as unknown as Record); + } return $multi(bHit, hit); }, }, diff --git a/Script/ts/src/Tests/Harness/TestRunner.ts b/Script/ts/src/Tests/Harness/TestRunner.ts index 0193368..3a078ca 100644 --- a/Script/ts/src/Tests/Harness/TestRunner.ts +++ b/Script/ts/src/Tests/Harness/TestRunner.ts @@ -145,28 +145,41 @@ export function GetSummary(): SuiteSummary { }; } -export function PrintReport(): SuiteSummary { - const summary = GetSummary(); +export function FormatReport(summary?: SuiteSummary): string { + const s = summary ?? GetSummary(); + const lines: string[] = []; let lastSuite = ""; - for (let i = 0; i < summary.results.length; i++) { - const r = summary.results[i]; + for (let i = 0; i < s.results.length; i++) { + const r = s.results[i]; if (r.suite !== lastSuite) { lastSuite = r.suite; - print(string.format("\n[%s]", r.suite)); + lines[lines.length] = ""; + lines[lines.length] = string.format("[%s]", r.suite); } if (r.passed) { - print(string.format(" PASS %s", r.name)); + lines[lines.length] = string.format(" PASS %s", r.name); } else { - print(string.format(" FAIL %s\n -> %s", r.name, r.errorMessage ?? "unknown error")); + lines[lines.length] = string.format( + " FAIL %s\n -> %s", + r.name, + r.errorMessage ?? "unknown error" + ); } } - print( - string.format( - "\n========================================\nTotal: %d | Passed: %d | Failed: %d\n========================================", - summary.total, - summary.passed, - summary.failed - ) + lines[lines.length] = ""; + lines[lines.length] = "========================================"; + lines[lines.length] = string.format( + "Total: %d | Passed: %d | Failed: %d", + s.total, + s.passed, + s.failed ); + lines[lines.length] = "========================================"; + return table.concat(lines, "\n"); +} + +export function PrintReport(): SuiteSummary { + const summary = GetSummary(); + print(FormatReport(summary)); return summary; } diff --git a/Script/ts/src/Tests/UE/UERuntimeSuite.ts b/Script/ts/src/Tests/UE/UERuntimeSuite.ts new file mode 100644 index 0000000..c5c718f --- /dev/null +++ b/Script/ts/src/Tests/UE/UERuntimeSuite.ts @@ -0,0 +1,364 @@ +/** @noSelfInFile */ + +import { + Reset, + PrintReport, + Suite, + Test, + AssertEqual, + AssertNear, + AssertTrue, + AssertFalse, + AssertNotNil, + AssertNil, + AssertArrayEqual, + SuiteSummary, +} from "../Harness/TestRunner"; +import { RunBasicTypesAndControlFlowTests } from "../Syntax/BasicTypesAndControlFlow"; +import { RunFunctionsClosuresAndTuplesTests } from "../Syntax/FunctionsClosuresAndTuples"; +import { RunPureClassesAndGenericsTests } from "../Syntax/PureClassesAndGenerics"; +import { RunGameplayTests } from "../Gameplay/GameplaySuite"; +import { RunLua54PitfallsTests } from "../Extra/Lua54PitfallsTest"; +import * as EventBus from "../../Framework/EventBus"; +import * as HotReload from "../../Framework/HotReload"; +import { + VerifyTArrayOperations, + VerifyTMapOperations, + VerifyTSetOperations, +} from "../UnLuaExamples/Ex06_NativeContainers"; +import type UnLuaBaseActor from "../Syntax/UnLuaBaseActor"; +import UnLuaBaseActorClass from "../Syntax/UnLuaBaseActor"; +import type UnLuaGrandChildActor from "../Syntax/UnLuaGrandChildActor"; +import type Ex01_HelloWorld from "../UnLuaExamples/Ex01_HelloWorld"; +import type Ex02_OverrideBlueprintEvents from "../UnLuaExamples/Ex02_OverrideBlueprintEvents"; +import type Ex04_DynamicSpawnedActor from "../UnLuaExamples/Ex04_DynamicSpawnedActor"; +import type Ex04_DynamicObject from "../UnLuaExamples/Ex04_DynamicObject"; +import type Ex07_CallLatentFunction from "../UnLuaExamples/Ex07_CallLatentFunction"; +import type Ex08_StructAndTrace from "../UnLuaExamples/Ex08_StructAndTrace"; +import type UETimerTestActor from "./UETimerTestActor"; + +function TickUEWorld(steps: number, deltaSeconds: number): void { + const tickFn = _G.__UE_TEST_TICK; + if (tickFn === undefined) { + return; + } + for (let i = 0; i < steps; i++) { + tickFn(deltaSeconds); + } +} + +export function RunUERuntimeSuite(world: UE.UWorld): void { + const canTickWorld = _G.__UE_TEST_TICK !== undefined; + + Suite("UE.RealEngineIntegration", () => { + Test("Real UE C++ TArray / TMap / TSet containers & native __pairs iteration", () => { + VerifyTArrayOperations(); + VerifyTMapOperations(); + VerifyTSetOperations(); + }); + + Test("Real UE SpawnActor + @unlua UnLuaBaseActor (Overridden, static methods, destructuring)", () => { + // UnLua 动态绑定按 UClass 缓存映射,每个独立 @unlua 测试类使用各自的轻量级原生 UClass + const actor = world.SpawnActor( + UE.ATargetPoint.StaticClass(), + UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + undefined, + undefined, + "Tests.Syntax.UnLuaBaseActor" + ); + AssertNotNil(actor); + AssertTrue(UE.UKismetSystemLibrary.IsValid(actor)); + AssertTrue(actor!.IsA(UE.AActor.StaticClass())); + + // SpawnActor 会自动触发 ReceiveBeginPlay + AssertEqual(actor!.GetHp(), 100); + AssertArrayEqual(actor!.GetTrace(), ["Base.ReceiveBeginPlay"]); + + // 解构形参 + 静态方法(冒号/点号) + AssertEqual(actor!.ApplyConfig({ name: "UEHero" }), "UEHero:100"); + AssertEqual(actor!.ApplyConfig({ name: "UEBoss", hp: 888 }), "UEBoss:888"); + AssertEqual(actor!.SumScores([10]), 15); + AssertEqual(actor!.SumScores([1, 2, 3, 4]), 10); + AssertEqual(UnLuaBaseActorClass.StaticWithSelf(25), 125); + AssertEqual(UnLuaBaseActorClass.StaticNoSelf(7, 8), 15); + AssertEqual(UnLuaBaseActorClass.StaticDocNoSelf(9), 27); + + actor!.K2_DestroyActor(); + }); + + Test("Real UE SpawnActor + 3-level @unlua inheritance (GrandChild -> Sub -> Base -> AActor)", () => { + const grand = world.SpawnActor( + UE.ATriggerBox.StaticClass(), + UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + undefined, + undefined, + "Tests.Syntax.UnLuaGrandChildActor" + ); + AssertNotNil(grand); + AssertArrayEqual(grand!.GetTrace(), [ + "Base.ReceiveBeginPlay", + "Sub.ReceiveBeginPlay", + "GrandChild.ReceiveBeginPlay", + ]); + AssertEqual(grand!.GetFaction(), "Ally"); + AssertEqual(grand!.GetTier(), 3); + AssertEqual(grand!.ComputeBonus(10), 33); + AssertEqual(grand!.SetupWithFaction({ name: "Knight", hp: 250 }, "Enemy"), "Knight:250[Enemy]"); + + grand!.K2_DestroyActor(); + }); + + Test("Real UE Ex01_HelloWorld & Ex02_OverrideBlueprintEvents lifecycle", () => { + const hello = world.SpawnActor( + UE.ATriggerSphere.StaticClass(), + UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + undefined, + undefined, + "Tests.UnLuaExamples.Ex01_HelloWorld" + ); + AssertNotNil(hello); + AssertTrue(string.find(hello!.GetGreeting(), "Hello UnLua from TypeScript", 1, true)[0] !== undefined); + hello!.K2_DestroyActor(); + + const eventsActor = world.SpawnActor( + UE.ATriggerCapsule.StaticClass(), + UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + undefined, + undefined, + "Tests.UnLuaExamples.Ex02_OverrideBlueprintEvents" + ); + AssertNotNil(eventsActor); + const events = eventsActor!.GetEvents(); + AssertTrue(events.length >= 2); + AssertEqual(events[0], "Initialize"); + + eventsActor!.K2_DestroyActor(); + }); + + Test("Real UE Ex04 DynamicBinding: SpawnActor, SpawnActorEx & UE.NewObject with Initializer", () => { + const spawned = world.SpawnActor( + UE.APlayerStart.StaticClass(), + UE.FTransform(UE.FRotator(0, 90, 0).ToQuat(), UE.FVector(100, 200, 300), UE.FVector(1, 1, 1)), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + undefined, + undefined, + "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", + { InitTag: "RealUESpawn", InitPower: 555 } + ); + AssertNotNil(spawned); + AssertEqual(spawned!.GetInitTag(), "RealUESpawn"); + AssertEqual(spawned!.GetInitPower(), 555); + AssertTrue(spawned!.IsBeginPlayCalled()); + spawned!.K2_DestroyActor(); + + const params = UE.FActorSpawnParameters(); + params.bNoFail = true; + params.SpawnCollisionHandlingOverride = UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn; + const spawnedEx = world.SpawnActorEx( + UE.APlayerStart.StaticClass(), + UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(10, 20, 30), UE.FVector(1, 1, 1)), + { InitTag: "RealUESpawnEx", InitPower: 777 }, + "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", + params + ); + AssertNotNil(spawnedEx); + AssertEqual(spawnedEx!.GetInitTag(), "RealUESpawnEx"); + AssertEqual(spawnedEx!.GetInitPower(), 777); + spawnedEx!.K2_DestroyActor(); + + // 注意:UnLua 不允许直接对基类 UObject 绑定模块,且需使用非抽象的具体 UObject 子类 + const dynObj = UE.NewObject( + UE.ULuaBundleAsset.StaticClass(), + world, + "RealUEDynObj", + "Tests.UnLuaExamples.Ex04_DynamicObject", + { Seed: 10 } + ); + AssertNotNil(dynObj); + AssertEqual(dynObj.GetSeed(), 10); + AssertEqual(dynObj.NextValue(), 21); + AssertEqual(dynObj.NextValue(), 43); + }); + + Test("Real UE Ex08 Struct math, K2_SetActorLocation & LineTraceSingle multi-return", () => { + const actor = world.SpawnActor( + UE.ATextRenderActor.StaticClass(), + UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + undefined, + undefined, + "Tests.UnLuaExamples.Ex08_StructAndTrace" + ); + AssertNotNil(actor); + + const [size, dot, dist] = actor!.ComputeVectorMath(); + AssertNear(size, 13, 1e-3); + AssertNear(dot, 0, 1e-3); + AssertNear(dist, 13, 1e-3); + + // 1. 验证传入复用 OutHit 原地写入(零 GC) + const [bHit, hitDist, impact] = actor!.TraceForward(500); + AssertFalse(bHit); // 空测试世界无阻挡物 + AssertEqual(type(hitDist), "number"); + AssertNotNil(impact); + + // 2. 验证传入 undefined 触发 UnLua 多返回值分配 + const [bHit2, outHit2] = actor!.TraceForwardMultiReturn(500); + AssertFalse(bHit2); + AssertNotNil(outHit2); + + actor!.K2_DestroyActor(); + }); + + Test("Real UE UnLua.Ref / UnLua.Unref & FWeakObjectPtr validity", () => { + const obj = UE.NewObject(UE.UObjectLibrary.StaticClass(), world, "WeakRefTarget"); + AssertTrue(UE.UKismetSystemLibrary.IsValid(obj)); + + const refProxy = UnLua.Ref(obj); + AssertNotNil(refProxy); + + // UnLua C++ 中 FWeakObjectPtr 构造必须传入 1 个 UObject 参数 + const weak = UE.FWeakObjectPtr(obj); + AssertTrue(weak.IsValid()); + AssertNotNil(weak.Get()); + + weak.Reset(); + AssertFalse(weak.IsValid()); + AssertNil(weak.Get()); + + UnLua.Unref(obj); + }); + + Test("Real UE ALuaDemoActor (IUnLuaInterface static binding) + EventBus + Tick + EndPlay", () => { + EventBus.Clear(); + const demoActor = world.SpawnActor( + UE.ALuaDemoActor.StaticClass(), + UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 100), UE.FVector(1, 1, 1)), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn + ); + AssertNotNil(demoActor); + AssertTrue(demoActor!.IsA(UE.ALuaDemoActor.StaticClass())); + + // Spawn 时已自动通过 IUnLuaInterface 绑定 Game.LuaDemoActor 并执行 ReceiveBeginPlay + const initText = demoActor!.GetStatusTextString(); + AssertTrue(string.find(initText, "UnLua Active", 1, true)[0] !== undefined); + AssertTrue(string.find(initText, "Pings: 0", 1, true)[0] !== undefined); + + if (canTickWorld) { + TickUEWorld(5, 0.05); + } + + // 触发 EventBus Ping,验证 C++ 3D 文本实时更新 + EventBus.Emit("Demo.Ping", "UERealEngineTest"); + const pingedText = demoActor!.GetStatusTextString(); + AssertTrue(string.find(pingedText, "Pings: 1", 1, true)[0] !== undefined); + AssertTrue(string.find(pingedText, "Color: Gold", 1, true)[0] !== undefined); + + // 验证 ALuaDemoActor 位置移动(带 SceneRoot 组件) + const [bMoved] = demoActor!.K2_SetActorLocation(UE.FVector(120, 240, 360), false, undefined, true); + AssertTrue(bMoved); + const loc = demoActor!.K2_GetActorLocation(); + AssertNear(loc.X, 120, 1e-2); + AssertNear(loc.Y, 240, 1e-2); + AssertNear(loc.Z, 360, 1e-2); + + demoActor!.K2_DestroyActor(); + EventBus.Clear(); + }); + + if (canTickWorld) { + Test("Real UE FTimerManager + K2_SetTimerDelegate(UnLua.Delegate) ticked by UWorld", () => { + const timerActor = world.SpawnActor( + UE.ACameraActor.StaticClass(), + UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + undefined, + undefined, + "Tests.UE.UETimerTestActor" + ); + AssertNotNil(timerActor); + AssertTrue(timerActor!.IsTimerActive()); + AssertEqual(timerActor!.GetTimerCount(), 0); + + // 推进真实 UWorld 0.5s(FTimerManager 首帧激活 Pending 列表,后续每 0.1s 触发一次,应 >= 3 次) + TickUEWorld(10, 0.05); + AssertTrue(timerActor!.GetTimerCount() >= 3); + + const countBeforeStop = timerActor!.GetTimerCount(); + timerActor!.StopTimer(); + AssertFalse(timerActor!.IsTimerActive()); + + TickUEWorld(6, 0.05); + AssertEqual(timerActor!.GetTimerCount(), countBeforeStop); + + timerActor!.K2_DestroyActor(); + }); + + Test("Real UE FLatentActionManager + UKismetSystemLibrary.Delay coroutine (Ex07)", () => { + const latentActor = world.SpawnActor( + UE.ADecalActor.StaticClass(), + UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), + UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, + undefined, + undefined, + "Tests.UnLuaExamples.Ex07_CallLatentFunction" + ); + AssertNotNil(latentActor); + AssertArrayEqual(latentActor!.GetSteps(), ["Step1:Start"]); + AssertFalse(latentActor!.IsCompleted()); + + // 推进 0.6s -> 越过第一个 0.5s Delay + TickUEWorld(6, 0.1); + AssertArrayEqual(latentActor!.GetSteps(), ["Step1:Start", "Step2:After0.5s"]); + AssertFalse(latentActor!.IsCompleted()); + + // 再推进 1.1s -> 越过第二个 1.0s Delay + TickUEWorld(11, 0.1); + AssertArrayEqual(latentActor!.GetSteps(), [ + "Step1:Start", + "Step2:After0.5s", + "Step3:Done", + ]); + AssertTrue(latentActor!.IsCompleted()); + + latentActor!.K2_DestroyActor(); + }); + } + + Test("Real UE HotReload.ReloadModule validates arguments and emits events", () => { + EventBus.Clear(); + const [badOk] = HotReload.ReloadModule(""); + AssertFalse(badOk); + const [ok] = HotReload.ReloadModule("Framework.Log"); + AssertTrue(ok); + EventBus.Clear(); + }); + }); +} + +/** + * 在真实 UE 5.8 + UnLua 2.3.6 环境下运行的统一入口。 + * 可由 RunLuaTestsCommandlet 或编辑器控制台命令 `Lua.RunTests` 调用。 + */ +export function RunAllInUE(world?: UE.UWorld): SuiteSummary { + const targetWorld = world ?? _G.__UE_TEST_WORLD; + Reset(); + + // 1. 纯逻辑与语法测试(运行在 UnLua 内嵌 Lua 5.4.3 VM 中) + RunBasicTypesAndControlFlowTests(); + RunFunctionsClosuresAndTuplesTests(); + RunPureClassesAndGenericsTests(); + RunGameplayTests(); + RunLua54PitfallsTests(); + + // 2. 真实 UE 5.8 引擎 + UnLua 反射/绑定/容器/定时器/协程集成测试 + if (targetWorld !== undefined) { + RunUERuntimeSuite(targetWorld); + } + + return PrintReport(); +} diff --git a/Script/ts/src/Tests/UE/UETimerTestActor.ts b/Script/ts/src/Tests/UE/UETimerTestActor.ts new file mode 100644 index 0000000..34161d2 --- /dev/null +++ b/Script/ts/src/Tests/UE/UETimerTestActor.ts @@ -0,0 +1,43 @@ +/** + * 用于真实 UE 5.8 环境下测试 K2_SetTimerDelegate + UnLua.Delegate(this, this.OnTimer) + * 与真实 UWorld::Tick -> FTimerManager 调度的 @unlua Actor。 + */ +@unlua +export default class UETimerTestActor extends UE.AActor { + private timerCount!: number; + private timerHandle!: UE.FTimerHandle; + + ReceiveBeginPlay(): void { + super.ReceiveBeginPlay(); + this.timerCount = 0; + this.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate( + UnLua.Delegate(this, this.OnTimerTick), + 0.1, + true + ); + } + + OnTimerTick(): void { + if (!UE.UKismetSystemLibrary.IsValid(this)) { + return; + } + this.timerCount++; + } + + StopTimer(): void { + UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(this, this.timerHandle); + } + + GetTimerCount(): number { + return this.timerCount; + } + + IsTimerActive(): boolean { + return UE.UKismetSystemLibrary.K2_IsTimerActiveHandle(this, this.timerHandle); + } + + ReceiveEndPlay(EndPlayReason: UE.EEndPlayReason): void { + this.StopTimer(); + super.ReceiveEndPlay(EndPlayReason); + } +} diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex06_NativeContainers.ts b/Script/ts/src/Tests/UnLuaExamples/Ex06_NativeContainers.ts index c2a6386..7b3a1e9 100644 --- a/Script/ts/src/Tests/UnLuaExamples/Ex06_NativeContainers.ts +++ b/Script/ts/src/Tests/UnLuaExamples/Ex06_NativeContainers.ts @@ -38,8 +38,8 @@ export function VerifyTArrayOperations(): void { AssertTrue(arr.Contains(25)); AssertFalse(arr.Contains(999)); - // AddUnique - AssertEqual(arr.AddUnique(25), 0); + // AddUnique:UnLua C++ 中若元素已存在,返回已有元素的 1-based 索引;否则追加并返回新索引 + AssertEqual(arr.AddUnique(25), 2); AssertEqual(arr.AddUnique(40), 4); AssertEqual(arr.Length(), 4); diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex08_StructAndTrace.ts b/Script/ts/src/Tests/UnLuaExamples/Ex08_StructAndTrace.ts index 33ba747..6a75dbe 100644 --- a/Script/ts/src/Tests/UnLuaExamples/Ex08_StructAndTrace.ts +++ b/Script/ts/src/Tests/UnLuaExamples/Ex08_StructAndTrace.ts @@ -21,10 +21,11 @@ export default class Ex08_StructAndTrace extends UE.AActor { ComputeVectorMath(): LuaMultiReturn<[number, number, number]> { const a = UE.FVector(3, 4, 0); const b = UE.FVector(0, 0, 12); - const c = a.Add(b); // (3, 4, 12), size = 13 const dot = a.Dot(b); // 0 - const dist = UE.FVector.Dist(UE.FVector(0, 0, 0), c); // 13 - return $multi(c.Size(), dot, dist); + // UnLua C++ 中 FVector:Add(b) 原地修改 self(无返回值),零额外结构体分配 + a.Add(b); // a 变为 (3, 4, 12), size = 13 + const dist = UE.FVector.Dist(UE.FVector(0, 0, 0), a); // 13 + return $multi(a.Size(), dot, dist); } TraceForward(distance: number): LuaMultiReturn<[boolean, number, UE.FVector]> { @@ -32,7 +33,9 @@ export default class Ex08_StructAndTrace extends UE.AActor { this._tmpStart.Set(origin.X, origin.Y, origin.Z); this._tmpEnd.Set(origin.X + distance, origin.Y, origin.Z); - const [bHit, hit] = UE.UKismetSystemLibrary.LineTraceSingle( + // UnLua 中传入已分配的 Out 参数(this._tmpHit)时会原地写入该结构体(零 GC),不再作为第二个返回值压栈; + // 传入 undefined 时才新分配并作为第二个返回值返回。此处同时兼容复用与多返回值模式。 + const [bHit, returnedHit] = UE.UKismetSystemLibrary.LineTraceSingle( this, this._tmpStart, this._tmpEnd, @@ -43,9 +46,28 @@ export default class Ex08_StructAndTrace extends UE.AActor { this._tmpHit, true ); + const hit = returnedHit ?? this._tmpHit; return $multi(bHit, hit.Distance, hit.ImpactPoint); } + TraceForwardMultiReturn(distance: number): LuaMultiReturn<[boolean, UE.FHitResult]> { + const origin = this.K2_GetActorLocation(); + this._tmpStart.Set(origin.X, origin.Y, origin.Z); + this._tmpEnd.Set(origin.X + distance, origin.Y, origin.Z); + + return UE.UKismetSystemLibrary.LineTraceSingle( + this, + this._tmpStart, + this._tmpEnd, + UE.ETraceTypeQuery.TraceTypeQuery1, + false, + this._ignoreActors, + UE.EDrawDebugTrace.None, + undefined, + true + ); + } + TeleportTo(x: number, y: number, z: number): boolean { const target = UE.FVector(x, y, z); const [bMoved] = this.K2_SetActorLocation(target, false, this._tmpHit, true); diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.ts b/Script/ts/src/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.ts index 5923def..e663d96 100644 --- a/Script/ts/src/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.ts +++ b/Script/ts/src/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.ts @@ -6,14 +6,14 @@ export default class Ex09_AssetRefAndUMG extends UE.UUserWidget { private loadedAsset!: UE.UObject | undefined; private refProxy!: unknown; - private weakRef!: UE.FWeakObjectPtr; + private weakRef!: UE.FWeakObjectPtr | undefined; private isConstructed!: boolean; private isDestructed!: boolean; Initialize(_Initializer?: unknown): void { this.isConstructed = false; this.isDestructed = false; - this.weakRef = UE.FWeakObjectPtr(); + this.weakRef = undefined; } Construct(): void { @@ -21,7 +21,7 @@ export default class Ex09_AssetRefAndUMG extends UE.UUserWidget { this.loadedAsset = UE.UObject.Load("/Game/UI/Textures/T_Icon.T_Icon"); if (this.loadedAsset !== undefined) { this.refProxy = UnLua.Ref(this.loadedAsset); - this.weakRef.Set(this.loadedAsset); + this.weakRef = UE.FWeakObjectPtr(this.loadedAsset); } } @@ -45,11 +45,14 @@ export default class Ex09_AssetRefAndUMG extends UE.UUserWidget { this.refProxy = undefined; this.loadedAsset = undefined; } - this.weakRef.Reset(); + if (this.weakRef !== undefined) { + this.weakRef.Reset(); + this.weakRef = undefined; + } } HasValidWeakAsset(): boolean { - return this.weakRef.IsValid(); + return this.weakRef !== undefined && this.weakRef.IsValid(); } IsConstructed(): boolean { diff --git a/Script/ts/types/project.d.ts b/Script/ts/types/project.d.ts index f97ddde..b93ea08 100644 --- a/Script/ts/types/project.d.ts +++ b/Script/ts/types/project.d.ts @@ -12,3 +12,5 @@ interface LuaPackageTable { } declare var GameFramework: Record | undefined; +declare var __UE_TEST_WORLD: UE.UWorld | undefined; +declare var __UE_TEST_TICK: ((this: void, deltaSeconds: number) => void) | undefined; diff --git a/Script/ts/types/ue/Script/CoreUObject.d.ts b/Script/ts/types/ue/Script/CoreUObject.d.ts index ae9093a..1063d4d 100644 --- a/Script/ts/types/ue/Script/CoreUObject.d.ts +++ b/Script/ts/types/ue/Script/CoreUObject.d.ts @@ -1434,10 +1434,10 @@ declare namespace UE { X: number; Y: number; Set(X?: number, Y?: number): void; - Add(other: FIntPoint | number): FIntPoint; - Sub(other: FIntPoint | number): FIntPoint; - Mul(other: FIntPoint | number): FIntPoint; - Div(other: FIntPoint | number): FIntPoint; + Add(other: FIntPoint | number): void; + Sub(other: FIntPoint | number): void; + Mul(other: FIntPoint | number): void; + Div(other: FIntPoint | number): void; Size(): number; SizeSquared(): number; } @@ -1457,10 +1457,10 @@ declare namespace UE { Z: number; Set(X?: number, Y?: number, Z?: number): void; SizeSquared(): number; - Add(other: FIntVector | number): FIntVector; - Sub(other: FIntVector | number): FIntVector; - Mul(other: FIntVector | number): FIntVector; - Div(other: FIntVector | number): FIntVector; + Add(other: FIntVector | number): void; + Sub(other: FIntVector | number): void; + Mul(other: FIntVector | number): void; + Div(other: FIntVector | number): void; Size(): number; } function FIntVector(this: void): FIntVector; @@ -1487,10 +1487,10 @@ declare namespace UE { B: number; A: number; Set(R?: number, G?: number, B?: number, A?: number): void; - Add(other: FLinearColor): FLinearColor; - Sub(other: FLinearColor): FLinearColor; - Mul(other: FLinearColor | number): FLinearColor; - Div(other: FLinearColor | number): FLinearColor; + Add(other: FLinearColor): void; + Sub(other: FLinearColor): void; + Mul(other: FLinearColor | number): void; + Div(other: FLinearColor | number): void; ToFColor(P0: boolean): FColor; Clamp(P0: number, P1: number): FLinearColor; } @@ -1727,7 +1727,7 @@ declare namespace UE { Set(X?: number, Y?: number, Z?: number, W?: number): void; Normalize(Tolerance?: number): void; GetNormalized(Tolerance?: number): FQuat; - Mul(other: FQuat | number): FQuat; + Mul(other: FQuat | number): void; IsNormalized(): boolean; Size(): number; SizeSquared(): number; @@ -1852,9 +1852,9 @@ declare namespace UE { GetRightVector(Out?: FVector): FVector; GetUpVector(Out?: FVector): FVector; GetUnitAxis(Axis: EAxis, Out?: FVector): FVector; - Add(other: FRotator): FRotator; - Sub(other: FRotator): FRotator; - Mul(scale: number): FRotator; + Add(other: FRotator): void; + Sub(other: FRotator): void; + Mul(scale: number): void; Normalize(): void; GetNormalized(): FRotator; RotateVector(P0: FVector): FVector; @@ -2094,7 +2094,7 @@ declare namespace UE { Scale3D: FVector; Blend(B: FTransform, C: FTransform, Alpha: number): void; BlendWith(B: FTransform, Alpha: number): void; - Mul(other: FTransform | number): FTransform; + Mul(other: FTransform | number): void; Inverse(): FTransform; TransformPosition(P0: FVector): FVector; TransformPositionNoScale(P0: FVector): FVector; @@ -2241,10 +2241,10 @@ declare namespace UE { Z: number; Set(X?: number, Y?: number, Z?: number): void; Normalize(Tolerance?: number): boolean; - Add(other: FVector | number): FVector; - Sub(other: FVector | number): FVector; - Mul(other: FVector | number): FVector; - Div(other: FVector | number): FVector; + Add(other: FVector | number): void; + Sub(other: FVector | number): void; + Mul(other: FVector | number): void; + Div(other: FVector | number): void; Dot(P0: FVector): number; Cross(P0: FVector): FVector; Size(): number; @@ -2273,10 +2273,10 @@ declare namespace UE { Set(X?: number, Y?: number): void; Normalize(Tolerance?: number): void; IsNormalized(): boolean; - Add(other: FVector2D | number): FVector2D; - Sub(other: FVector2D | number): FVector2D; - Mul(other: FVector2D | number): FVector2D; - Div(other: FVector2D | number): FVector2D; + Add(other: FVector2D | number): void; + Sub(other: FVector2D | number): void; + Mul(other: FVector2D | number): void; + Div(other: FVector2D | number): void; Dot(P0: FVector2D): number; Cross(P0: FVector2D): number; Size(): number; @@ -2317,10 +2317,10 @@ declare namespace UE { Z: number; W: number; Set(X?: number, Y?: number, Z?: number, W?: number): void; - Add(other: FVector4 | number): FVector4; - Sub(other: FVector4 | number): FVector4; - Mul(other: FVector4 | number): FVector4; - Div(other: FVector4 | number): FVector4; + Add(other: FVector4 | number): void; + Sub(other: FVector4 | number): void; + Mul(other: FVector4 | number): void; + Div(other: FVector4 | number): void; Cross(P0: FVector4): FVector4; Size(): number; Size3(): number; @@ -2427,7 +2427,6 @@ declare namespace UE { static Load(this: void, classPath: string): T | undefined; IsChildOf(targetClass: UClass): boolean; GetDefaultObject(): T; - static StaticClass(this: void): UClass; } class UClassCookedMetaData extends UCookedMetaDataBase { @@ -2700,7 +2699,6 @@ declare namespace UE { Release(): void; Destroy(): void; static Load(this: void, objectPath: string): T | undefined; - static StaticClass(this: void): UClass; } class UObjectProperty extends UObjectPropertyBase { diff --git a/Source/UnrealLuaDemo/UnrealLuaDemo.cpp b/Source/UnrealLuaDemo/UnrealLuaDemo.cpp index 7ea1f37..fba8f9f 100644 --- a/Source/UnrealLuaDemo/UnrealLuaDemo.cpp +++ b/Source/UnrealLuaDemo/UnrealLuaDemo.cpp @@ -2,7 +2,12 @@ #include "UnrealLuaDemo.h" #include "HotUpdate/LuaHotUpdateSubsystem.h" +#include "Engine/Engine.h" +#include "Engine/World.h" #include "HAL/IConsoleManager.h" +#include "UnLua.h" +#include "LuaEnv.h" +#include "lua.hpp" DEFINE_LOG_CATEGORY(LogUnrealLuaDemo); @@ -34,12 +39,51 @@ void FUnrealLuaDemoModule::StartupModule() }), ECVF_Default); + RunTestsCmd = IConsoleManager::Get().RegisterConsoleCommand( + TEXT("Lua.RunTests"), + TEXT("Run compiled TypeScript -> UnLua runtime test suite in the current active game/PIE UWorld."), + FConsoleCommandWithWorldDelegate::CreateLambda([](UWorld* World) + { + TMap& AllEnvs = UnLua::FLuaEnv::GetAll(); + if (AllEnvs.Num() == 0) + { + UE_LOG(LogUnrealLuaDemo, Warning, TEXT("Lua.RunTests: No active UnLua environment (start PIE first).")); + return; + } + for (const TPair& Pair : AllEnvs) + { + if (UnLua::FLuaEnv* Env = Pair.Value) + { + lua_State* L = Env->GetMainState(); + if (L && World) + { + UnLua::PushUObject(L, World); + lua_setglobal(L, "__UE_TEST_WORLD"); + } + Env->DoString(TEXT("require('Tests.UE.UERuntimeSuite').RunAllInUE(_G.__UE_TEST_WORLD)"), TEXT("Lua.RunTests")); + if (L) + { + lua_pushnil(L); + lua_setglobal(L, "__UE_TEST_WORLD"); + } + break; + } + } + }), + ECVF_Default); + UE_LOG(LogUnrealLuaDemo, Log, TEXT("UnrealLuaDemo module started. Hot-update script dir: %s"), *ULuaHotUpdateSubsystem::GetHotUpdateScriptDir()); } void FUnrealLuaDemoModule::ShutdownModule() { + if (RunTestsCmd) + { + IConsoleManager::Get().UnregisterConsoleObject(RunTestsCmd); + RunTestsCmd = nullptr; + } + if (HotReloadCmd) { IConsoleManager::Get().UnregisterConsoleObject(HotReloadCmd); diff --git a/Source/UnrealLuaDemo/UnrealLuaDemo.h b/Source/UnrealLuaDemo/UnrealLuaDemo.h index 391d6f2..ef4b3e6 100644 --- a/Source/UnrealLuaDemo/UnrealLuaDemo.h +++ b/Source/UnrealLuaDemo/UnrealLuaDemo.h @@ -16,4 +16,5 @@ public: private: IConsoleObject* HotReloadCmd = nullptr; IConsoleObject* ReloadModuleCmd = nullptr; + IConsoleObject* RunTestsCmd = nullptr; }; diff --git a/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.cpp b/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.cpp new file mode 100644 index 0000000..c66c3c4 --- /dev/null +++ b/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.cpp @@ -0,0 +1,172 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "RunLuaTestsCommandlet.h" +#include "UnrealLuaDemoEditor.h" +#include "Engine/Engine.h" +#include "Engine/World.h" +#include "GameFramework/WorldSettings.h" +#include "UnLua.h" +#include "UnLuaModule.h" +#include "LuaEnv.h" +#include "lua.hpp" + +namespace +{ + UWorld* GCurrentLuaTestWorld = nullptr; + + int LuaTestWorldTick(lua_State* L) + { + const float DeltaSeconds = lua_gettop(L) >= 1 ? static_cast(luaL_checknumber(L, 1)) : 0.016f; + if (GCurrentLuaTestWorld && IsValid(GCurrentLuaTestWorld)) + { + // Advance GFrameCounter so FTimerManager::HasBeenTickedThisFrame() treats each call as a new engine frame. + ++GFrameCounter; + GCurrentLuaTestWorld->Tick(LEVELTICK_All, DeltaSeconds); + } + return 0; + } +} + +URunLuaTestsCommandlet::URunLuaTestsCommandlet() +{ + IsClient = true; + IsEditor = true; + IsServer = false; + LogToConsole = true; + ShowErrorCount = true; +} + +int32 URunLuaTestsCommandlet::Main(const FString& Params) +{ + UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[RunLuaTestsCommandlet] Starting real UE + UnLua test runner...")); + + IUnLuaModule& UnLuaModule = IUnLuaModule::Get(); + const bool bWasActive = UnLuaModule.IsActive(); + if (!bWasActive) + { + UnLuaModule.SetActive(true); + } + + UWorld* TestWorld = UWorld::CreateWorld(EWorldType::Game, false, TEXT("LuaTestWorld")); + if (!TestWorld) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaTestsCommandlet] Failed to create UWorld.")); + if (!bWasActive) + { + UnLuaModule.SetActive(false); + } + return 1; + } + + FWorldContext& WorldContext = GEngine->CreateNewWorldContext(EWorldType::Game); + WorldContext.SetCurrentWorld(TestWorld); + + TestWorld->InitializeActorsForPlay(FURL()); + if (AWorldSettings* WorldSettings = TestWorld->GetWorldSettings()) + { + WorldSettings->NotifyBeginPlay(); + WorldSettings->NotifyMatchStarted(); + } + TestWorld->BeginPlay(); + + GCurrentLuaTestWorld = TestWorld; + + int32 ExitCode = 1; + UnLua::FLuaEnv* Env = UnLuaModule.GetEnv(TestWorld); + if (!Env) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaTestsCommandlet] Failed to obtain UnLua FLuaEnv.")); + } + else + { + lua_State* L = Env->GetMainState(); + if (L) + { + UnLua::PushUObject(L, TestWorld); + lua_setglobal(L, "__UE_TEST_WORLD"); + + lua_pushcfunction(L, &LuaTestWorldTick); + lua_setglobal(L, "__UE_TEST_TICK"); + + const FString RunChunk = TEXT( + "local suite = require('Tests.UE.UERuntimeSuite')\n" + "local runner = require('Tests.Harness.TestRunner')\n" + "local summary = suite.RunAllInUE(_G.__UE_TEST_WORLD)\n" + "_G.__UE_TEST_TOTAL = summary.total or 0\n" + "_G.__UE_TEST_PASSED = summary.passed or 0\n" + "_G.__UE_TEST_FAILED = summary.failed or 0\n" + "_G.__UE_TEST_REPORT = runner.FormatReport(summary)\n" + ); + + const bool bExecOk = Env->DoString(RunChunk, TEXT("RunLuaTestsCommandlet")); + + lua_getglobal(L, "__UE_TEST_REPORT"); + const char* ReportUtf8 = lua_tostring(L, -1); + const FString ReportText = ReportUtf8 ? UTF8_TO_TCHAR(ReportUtf8) : FString(); + lua_pop(L, 1); + + if (!ReportText.IsEmpty()) + { + TArray Lines; + ReportText.ParseIntoArrayLines(Lines, false); + for (const FString& Line : Lines) + { + UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("%s"), *Line); + } + } + + lua_getglobal(L, "__UE_TEST_TOTAL"); + const int32 Total = static_cast(lua_tointeger(L, -1)); + lua_pop(L, 1); + + lua_getglobal(L, "__UE_TEST_PASSED"); + const int32 Passed = static_cast(lua_tointeger(L, -1)); + lua_pop(L, 1); + + lua_getglobal(L, "__UE_TEST_FAILED"); + const int32 Failed = static_cast(lua_tointeger(L, -1)); + lua_pop(L, 1); + + // Clear test globals before teardown + lua_pushnil(L); + lua_setglobal(L, "__UE_TEST_WORLD"); + lua_pushnil(L); + lua_setglobal(L, "__UE_TEST_TICK"); + lua_pushnil(L); + lua_setglobal(L, "__UE_TEST_REPORT"); + + if (!bExecOk) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaTestsCommandlet] Lua execution error while running Tests.UE.UERuntimeSuite.")); + ExitCode = 1; + } + else if (Total <= 0 || Failed > 0) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, + TEXT("[RunLuaTestsCommandlet] UE Lua tests FAILED (Total=%d, Passed=%d, Failed=%d)."), + Total, Passed, Failed); + ExitCode = 1; + } + else + { + UE_LOG(LogUnrealLuaDemoEditor, Display, + TEXT("[RunLuaTestsCommandlet] All UE Lua tests PASSED (Total=%d, Passed=%d, Failed=%d)."), + Total, Passed, Failed); + ExitCode = 0; + } + } + } + + GCurrentLuaTestWorld = nullptr; + + TestWorld->EndPlay(EEndPlayReason::Quit); + GEngine->DestroyWorldContext(TestWorld); + TestWorld->DestroyWorld(false); + + if (!bWasActive) + { + UnLuaModule.SetActive(false); + } + + return ExitCode; +} diff --git a/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.h b/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.h new file mode 100644 index 0000000..8a3003f --- /dev/null +++ b/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.h @@ -0,0 +1,26 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "Commandlets/Commandlet.h" +#include "RunLuaTestsCommandlet.generated.h" + +/** + * Headless commandlet that boots a real UWorld + UnLua 2.3.6 Lua 5.4 runtime + * and executes the compiled TypeScript -> UnLua test suite (`Tests.UE.UERuntimeSuite`). + * + * Usage: + * UnrealEditor-Cmd -run=RunLuaTests -unattended -nop4 -nosplash -NullRHI + * (Optional: pass -UseLuaBundle to run tests directly from /Game/Generated/DA_LuaBundle) + */ +UCLASS() +class UNREALLUADEMOEDITOR_API URunLuaTestsCommandlet : public UCommandlet +{ + GENERATED_BODY() + +public: + URunLuaTestsCommandlet(); + + virtual int32 Main(const FString& Params) override; +}; diff --git a/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.Build.cs b/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.Build.cs index eb18bb8..ba9aa34 100644 --- a/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.Build.cs +++ b/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.Build.cs @@ -26,7 +26,9 @@ public class UnrealLuaDemoEditor : ModuleRules "Projects", "Slate", "SlateCore", - "ToolMenus" + "ToolMenus", + "UnLua", + "Lua" }); } }