test: add comprehensive ts2lua-unreal TS/Lua 5.4 test suites and upgrade to v0.2.2
This commit is contained in:
1 parent
ee2e62bb34
commit
3dd61c32a9
75 files changed
+9929
-10
No files matched your search
@@ -0,0 +1,157 @@
|
||||
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")
|
||||
function ____exports.RunHotReloadAndFrameworkTests()
|
||||
Suite(
|
||||
"Extra.FrameworkAndHotReload",
|
||||
function()
|
||||
Test(
|
||||
"EventBus: dedup, owner dispatch, mid-emit unsubscribe, OffAllForOwner and error isolation",
|
||||
function()
|
||||
EventBus.Clear()
|
||||
local received = {}
|
||||
local ownerA = {
|
||||
tag = "A",
|
||||
OnEvent = function(self, msg)
|
||||
received[#received + 1] = (self.tag .. ":") .. msg
|
||||
end
|
||||
}
|
||||
local ownerB = {
|
||||
tag = "B",
|
||||
OnEvent = function(self, msg)
|
||||
received[#received + 1] = (self.tag .. ":") .. msg
|
||||
EventBus.Off("Test.Ping", self.OnEvent, self)
|
||||
end
|
||||
}
|
||||
EventBus.On("Test.Ping", ownerA.OnEvent, ownerA)
|
||||
EventBus.On("Test.Ping", ownerA.OnEvent, ownerA)
|
||||
EventBus.On("Test.Ping", ownerB.OnEvent, ownerB)
|
||||
EventBus.On(
|
||||
"Test.Ping",
|
||||
function()
|
||||
error("intentional listener error")
|
||||
end
|
||||
)
|
||||
local afterErrorCalled = false
|
||||
EventBus.On(
|
||||
"Test.Ping",
|
||||
function()
|
||||
afterErrorCalled = true
|
||||
end
|
||||
)
|
||||
EventBus.Emit("Test.Ping", "hello")
|
||||
AssertArrayEqual(received, {"A:hello", "B:hello"})
|
||||
AssertTrue(afterErrorCalled)
|
||||
EventBus.Emit("Test.Ping", "world")
|
||||
AssertArrayEqual(received, {"A:hello", "B:hello", "A:world"})
|
||||
EventBus.OffAllForOwner(ownerA)
|
||||
EventBus.Emit("Test.Ping", "ignored")
|
||||
AssertArrayEqual(received, {"A:hello", "B:hello", "A:world"})
|
||||
EventBus.Clear()
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Bootstrap Init/Shutdown lifecycle and _G.GameFramework registration",
|
||||
function()
|
||||
local fakeGI = CreateBoundInstance({}, "ULuaGameInstance")
|
||||
Bootstrap.Init(fakeGI)
|
||||
AssertTrue(Bootstrap.IsInitialized)
|
||||
AssertEqual(Bootstrap.GameInstance, fakeGI)
|
||||
AssertNotNil(_G.GameFramework)
|
||||
Bootstrap.Shutdown()
|
||||
AssertFalse(Bootstrap.IsInitialized)
|
||||
AssertNil(Bootstrap.GameInstance)
|
||||
AssertNil(_G.GameFramework)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"HotReload.ReloadModule validates arguments and emits Before/After events",
|
||||
function()
|
||||
EventBus.Clear()
|
||||
local badOk, badErr = HotReload.ReloadModule("")
|
||||
AssertFalse(badOk)
|
||||
AssertEqual(badErr, "Invalid module name")
|
||||
local order = {}
|
||||
EventBus.On(
|
||||
HotReload.EVENT_BEFORE_RELOAD,
|
||||
function(modName)
|
||||
order[#order + 1] = "before:" .. modName
|
||||
end
|
||||
)
|
||||
EventBus.On(
|
||||
HotReload.EVENT_AFTER_RELOAD,
|
||||
function(modName)
|
||||
order[#order + 1] = "after:" .. modName
|
||||
end
|
||||
)
|
||||
local ok = HotReload.ReloadModule("Framework.Log")
|
||||
AssertTrue(ok)
|
||||
AssertArrayEqual(order, {"before:Framework.Log", "after:Framework.Log"})
|
||||
EventBus.Clear()
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"LuaDemoActor full integration: BeginPlay, Tick, Ping color cycle, HotReload event & EndPlay cleanup",
|
||||
function()
|
||||
ResetMockState()
|
||||
EventBus.Clear()
|
||||
local lastStatusText = ""
|
||||
local colorApplyCount = 0
|
||||
local rotationAddCount = 0
|
||||
local lastVerticalOffset = 0
|
||||
local demoActor = CreateBoundInstance(
|
||||
LuaDemoActor,
|
||||
"ALuaDemoActor",
|
||||
{
|
||||
SpinSpeed = 90,
|
||||
BobAmplitude = 20,
|
||||
BobFrequency = 2,
|
||||
SetStatusText = function(self, text)
|
||||
lastStatusText = text
|
||||
end,
|
||||
SetCubeColor = function(self, _color)
|
||||
colorApplyCount = colorApplyCount + 1
|
||||
end,
|
||||
AddCubeLocalRotation = function(self, _delta)
|
||||
rotationAddCount = rotationAddCount + 1
|
||||
end,
|
||||
SetCubeVerticalOffset = function(self, zOffset)
|
||||
lastVerticalOffset = zOffset
|
||||
end
|
||||
}
|
||||
)
|
||||
demoActor:ReceiveBeginPlay()
|
||||
AssertEqual(colorApplyCount, 1)
|
||||
AssertTrue((string.find(lastStatusText, "Pings: 0", 1, true)) ~= nil)
|
||||
demoActor:ReceiveTick(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")
|
||||
AssertTrue((string.find(lastStatusText, "Reloads: 1", 1, true)) ~= nil)
|
||||
demoActor:ReceiveEndPlay(UE.EEndPlayReason.Destroyed)
|
||||
EventBus.Emit("Demo.Ping", "AfterEndPlay")
|
||||
AssertEqual(colorApplyCount, 2)
|
||||
EventBus.Clear()
|
||||
end
|
||||
)
|
||||
end
|
||||
)
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,93 @@
|
||||
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 LifecycleSafetyActor = require("Tests.Extra.LifecycleSafetyActor")
|
||||
function ____exports.RunLifecycleAndMemoryTests()
|
||||
Suite(
|
||||
"Extra.LifecycleAndMemorySafety",
|
||||
function()
|
||||
Test(
|
||||
"multiple @unlua instances maintain isolated state (no shared class-table arrays)",
|
||||
function()
|
||||
ResetMockState()
|
||||
EventBus.Clear()
|
||||
local cls = LifecycleSafetyActor
|
||||
local a = CreateBoundInstance(cls, "AActor")
|
||||
local b = CreateBoundInstance(cls, "AActor")
|
||||
a:ReceiveBeginPlay()
|
||||
b:ReceiveBeginPlay()
|
||||
a:PushItem("only_in_a")
|
||||
b:PushItem("only_in_b")
|
||||
AssertArrayEqual(
|
||||
a:GetItems(),
|
||||
{"only_in_a"}
|
||||
)
|
||||
AssertArrayEqual(
|
||||
b:GetItems(),
|
||||
{"only_in_b"}
|
||||
)
|
||||
a:ReceiveEndPlay(UE.EEndPlayReason.Destroyed)
|
||||
b:ReceiveEndPlay(UE.EEndPlayReason.Destroyed)
|
||||
EventBus.Clear()
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"paired cleanup on ReceiveEndPlay prevents leaked EventBus, Delegate, Timer & manual Ref",
|
||||
function()
|
||||
ResetMockState()
|
||||
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)
|
||||
actor:ReceiveBeginPlay()
|
||||
actor:HoldManualRef(asset)
|
||||
AssertEqual(
|
||||
GetMockState().manualRefs[asset],
|
||||
1
|
||||
)
|
||||
EventBus.Emit("Lifecycle.Broadcast", "msg1")
|
||||
actor.OnTakeAnyDamage:Broadcast(
|
||||
actor,
|
||||
25,
|
||||
nil,
|
||||
nil,
|
||||
nil
|
||||
)
|
||||
AdvanceMockTime(1)
|
||||
AssertEqual(
|
||||
actor:GetReceivedEvents(),
|
||||
3
|
||||
)
|
||||
AssertTrue(weak:IsValid())
|
||||
actor:ReceiveEndPlay(UE.EEndPlayReason.Destroyed)
|
||||
actor:K2_DestroyActor()
|
||||
AssertFalse(actor.OnTakeAnyDamage:IsBound())
|
||||
AssertFalse(weak:IsValid())
|
||||
AssertNil(weak:Get())
|
||||
AssertNil(GetMockState().manualRefs[asset])
|
||||
EventBus.Emit("Lifecycle.Broadcast", "msg2")
|
||||
AdvanceMockTime(3)
|
||||
AssertEqual(
|
||||
actor:GetReceivedEvents(),
|
||||
3
|
||||
)
|
||||
EventBus.Clear()
|
||||
end
|
||||
)
|
||||
end
|
||||
)
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,54 @@
|
||||
local EventBus = require("Framework.EventBus")
|
||||
local LifecycleSafetyActor = UnLua.Class()
|
||||
function LifecycleSafetyActor.ReceiveBeginPlay(self)
|
||||
self.Overridden.ReceiveBeginPlay(self)
|
||||
self.items = {}
|
||||
self.receivedEvents = 0
|
||||
EventBus.On("Lifecycle.Broadcast", self.OnBroadcast, self)
|
||||
self.OnTakeAnyDamage:Add(self, self.OnDamaged)
|
||||
self.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate({self, self.OnHeartbeat}, 1, true)
|
||||
end
|
||||
function LifecycleSafetyActor.PushItem(self, item)
|
||||
self.items[#self.items + 1] = item
|
||||
end
|
||||
function LifecycleSafetyActor.GetItems(self)
|
||||
return self.items
|
||||
end
|
||||
function LifecycleSafetyActor.HoldManualRef(self, asset)
|
||||
self.keptRef = asset
|
||||
UnLua.Ref(asset)
|
||||
end
|
||||
function LifecycleSafetyActor.OnBroadcast(self, tag)
|
||||
if not UE.UKismetSystemLibrary.IsValid(self) then
|
||||
return
|
||||
end
|
||||
self.receivedEvents = self.receivedEvents + 1
|
||||
self.items[#self.items + 1] = tag
|
||||
end
|
||||
function LifecycleSafetyActor.OnDamaged(self, _DamagedActor, Damage, _DamageType, _InstigatedBy, _DamageCauser)
|
||||
if not UE.UKismetSystemLibrary.IsValid(self) then
|
||||
return
|
||||
end
|
||||
self.receivedEvents = self.receivedEvents + 1
|
||||
self.items[#self.items + 1] = "dmg:" .. tostring(Damage)
|
||||
end
|
||||
function LifecycleSafetyActor.OnHeartbeat(self)
|
||||
if not UE.UKismetSystemLibrary.IsValid(self) then
|
||||
return
|
||||
end
|
||||
self.receivedEvents = self.receivedEvents + 1
|
||||
end
|
||||
function LifecycleSafetyActor.GetReceivedEvents(self)
|
||||
return self.receivedEvents
|
||||
end
|
||||
function LifecycleSafetyActor.ReceiveEndPlay(self, EndPlayReason)
|
||||
EventBus.OffAllForOwner(self)
|
||||
self.OnTakeAnyDamage:Remove(self, self.OnDamaged)
|
||||
UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(self, self.timerHandle)
|
||||
if self.keptRef ~= nil then
|
||||
UnLua.Unref(self.keptRef)
|
||||
self.keptRef = nil
|
||||
end
|
||||
self.Overridden.ReceiveEndPlay(self, EndPlayReason)
|
||||
end
|
||||
return LifecycleSafetyActor
|
||||
@@ -0,0 +1,171 @@
|
||||
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 function EscapeLuaPattern(literal)
|
||||
local escaped = string.gsub(literal, "([%(%)%.%%%+%-%*%?%[%]%^%$])", "%%%1")
|
||||
return escaped
|
||||
end
|
||||
local function DeepCloneTable(src, seen)
|
||||
if type(src) ~= "table" then
|
||||
return src
|
||||
end
|
||||
local visited = seen or ({})
|
||||
local existing = visited[src]
|
||||
if existing ~= nil then
|
||||
return existing
|
||||
end
|
||||
local copy = {}
|
||||
visited[src] = copy
|
||||
for k, v in pairs(src) do
|
||||
copy[DeepCloneTable(k, visited)] = DeepCloneTable(v, visited)
|
||||
end
|
||||
return copy
|
||||
end
|
||||
function ____exports.RunLua54PitfallsTests()
|
||||
Suite(
|
||||
"Extra.Lua54PitfallsAndEdgeCases",
|
||||
function()
|
||||
Test(
|
||||
"Lua truthiness vs JS: explicit checks for 0 and empty string, ?? vs ||",
|
||||
function()
|
||||
local zero = 0
|
||||
local empty = ""
|
||||
AssertTrue(zero == 0)
|
||||
AssertTrue(empty == "")
|
||||
local ____AssertTrue_1 = AssertTrue
|
||||
local ____temp_0
|
||||
if zero then
|
||||
____temp_0 = true
|
||||
else
|
||||
____temp_0 = false
|
||||
end
|
||||
____AssertTrue_1(____temp_0)
|
||||
local ____AssertTrue_3 = AssertTrue
|
||||
local ____temp_2
|
||||
if empty then
|
||||
____temp_2 = true
|
||||
else
|
||||
____temp_2 = false
|
||||
end
|
||||
____AssertTrue_3(____temp_2)
|
||||
local optZero = 0
|
||||
local optEmpty = ""
|
||||
local optFalse = false
|
||||
local optNil = nil
|
||||
AssertEqual(optZero or 100, 0)
|
||||
AssertEqual(optEmpty or "fallback", "")
|
||||
local ____AssertEqual_5 = AssertEqual
|
||||
local ____optFalse_4 = optFalse
|
||||
if ____optFalse_4 == nil then
|
||||
____optFalse_4 = true
|
||||
end
|
||||
____AssertEqual_5(____optFalse_4, false)
|
||||
AssertEqual(optNil or 100, 100)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Lua 5.4 UTF-8 character counting for CJK game text vs byte length",
|
||||
function()
|
||||
local cnText = "你好UE5世界"
|
||||
AssertEqual(#cnText, 15)
|
||||
local charCount = utf8.len(cnText)
|
||||
AssertEqual(charCount, 7)
|
||||
local codes = {utf8.codepoint(cnText, 1, -1)}
|
||||
AssertEqual(#codes, 7)
|
||||
AssertEqual(codes[1], 20320)
|
||||
AssertEqual(codes[3], 85)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Lua pattern magic character escaping for literal search & replace",
|
||||
function()
|
||||
local raw = "Item[Epic]+10 (50.5%)"
|
||||
local escaped = EscapeLuaPattern("[Epic]+10 (50.5%)")
|
||||
local startIdx = string.find(raw, escaped)
|
||||
AssertTrue(startIdx ~= nil)
|
||||
local replaced = string.gsub(
|
||||
raw,
|
||||
EscapeLuaPattern("(50.5%)"),
|
||||
"(100%%)"
|
||||
)
|
||||
AssertEqual(replaced, "Item[Epic]+10 (100%)")
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"0-based TS array vs 1-based UE.TArray interop without sparse holes",
|
||||
function()
|
||||
local tsArr = {"first", "second", "third"}
|
||||
local ueArr = UE.TArray(UE.FString)
|
||||
do
|
||||
local i = 0
|
||||
while i < #tsArr do
|
||||
ueArr:Add(tsArr[i + 1])
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
AssertEqual(
|
||||
ueArr:Length(),
|
||||
#tsArr
|
||||
)
|
||||
AssertEqual(
|
||||
ueArr:Get(1),
|
||||
tsArr[1]
|
||||
)
|
||||
AssertEqual(
|
||||
ueArr:Get(3),
|
||||
tsArr[3]
|
||||
)
|
||||
local dense = {10, 20, 30, 40}
|
||||
local removeIdx = 1
|
||||
dense[removeIdx + 1] = dense[#dense]
|
||||
table.remove(dense)
|
||||
AssertEqual(#dense, 3)
|
||||
AssertArrayEqual(dense, {10, 40, 30})
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"deep clone plain tables safely including circular references",
|
||||
function()
|
||||
local original = {name = "Root", tags = {"a", "b"}}
|
||||
original.selfRef = original
|
||||
local cloned = DeepCloneTable(original)
|
||||
AssertEqual(cloned.name, "Root")
|
||||
AssertArrayEqual(cloned.tags, {"a", "b"})
|
||||
AssertTrue(cloned ~= original)
|
||||
AssertTrue(cloned.tags ~= original.tags)
|
||||
AssertEqual(cloned.selfRef, cloned)
|
||||
local ____cloned_tags_6 = cloned.tags
|
||||
____cloned_tags_6[#____cloned_tags_6 + 1] = "c"
|
||||
AssertEqual(#original.tags, 2)
|
||||
AssertEqual(#cloned.tags, 3)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"zero-GC hot-path Tick simulation with cached FVector/FRotator (10,000 frames)",
|
||||
function()
|
||||
local pos = UE.FVector(0, 0, 0)
|
||||
local vel = UE.FVector(10, 20, -5)
|
||||
local dt = 0.016
|
||||
do
|
||||
local frame = 0
|
||||
while frame < 10000 do
|
||||
pos.X = pos.X + vel.X * dt
|
||||
pos.Y = pos.Y + vel.Y * dt
|
||||
pos.Z = pos.Z + vel.Z * dt
|
||||
frame = frame + 1
|
||||
end
|
||||
end
|
||||
AssertNear(pos.X, 1600, 0.1)
|
||||
AssertNear(pos.Y, 3200, 0.1)
|
||||
AssertNear(pos.Z, -800, 0.1)
|
||||
end
|
||||
)
|
||||
end
|
||||
)
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,130 @@
|
||||
local ____lualib = require("lualib_bundle")
|
||||
local __TS__Class = ____lualib.__TS__Class
|
||||
local ____exports = {}
|
||||
____exports.BTCondition = __TS__Class()
|
||||
local BTCondition = ____exports.BTCondition
|
||||
BTCondition.name = "BTCondition"
|
||||
function BTCondition.prototype.____constructor(self, check)
|
||||
self.check = check
|
||||
end
|
||||
function BTCondition.prototype.Tick(self, ctx)
|
||||
return self.check(ctx) and 0 or 1
|
||||
end
|
||||
function BTCondition.prototype.Reset(self)
|
||||
end
|
||||
____exports.BTAction = __TS__Class()
|
||||
local BTAction = ____exports.BTAction
|
||||
BTAction.name = "BTAction"
|
||||
function BTAction.prototype.____constructor(self, action)
|
||||
self.action = action
|
||||
end
|
||||
function BTAction.prototype.Tick(self, ctx)
|
||||
return self.action(ctx)
|
||||
end
|
||||
function BTAction.prototype.Reset(self)
|
||||
end
|
||||
____exports.BTSequence = __TS__Class()
|
||||
local BTSequence = ____exports.BTSequence
|
||||
BTSequence.name = "BTSequence"
|
||||
function BTSequence.prototype.____constructor(self, children)
|
||||
self.runningIndex = 0
|
||||
self.children = children
|
||||
end
|
||||
function BTSequence.prototype.Tick(self, ctx)
|
||||
while self.runningIndex < #self.children do
|
||||
local status = self.children[self.runningIndex + 1]:Tick(ctx)
|
||||
if status == 2 then
|
||||
return 2
|
||||
end
|
||||
if status == 1 then
|
||||
self:Reset()
|
||||
return 1
|
||||
end
|
||||
self.runningIndex = self.runningIndex + 1
|
||||
end
|
||||
self:Reset()
|
||||
return 0
|
||||
end
|
||||
function BTSequence.prototype.Reset(self)
|
||||
self.runningIndex = 0
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.children do
|
||||
self.children[i + 1]:Reset()
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
____exports.BTSelector = __TS__Class()
|
||||
local BTSelector = ____exports.BTSelector
|
||||
BTSelector.name = "BTSelector"
|
||||
function BTSelector.prototype.____constructor(self, children)
|
||||
self.runningIndex = 0
|
||||
self.children = children
|
||||
end
|
||||
function BTSelector.prototype.Tick(self, ctx)
|
||||
while self.runningIndex < #self.children do
|
||||
local status = self.children[self.runningIndex + 1]:Tick(ctx)
|
||||
if status == 2 then
|
||||
return 2
|
||||
end
|
||||
if status == 0 then
|
||||
self:Reset()
|
||||
return 0
|
||||
end
|
||||
self.runningIndex = self.runningIndex + 1
|
||||
end
|
||||
self:Reset()
|
||||
return 1
|
||||
end
|
||||
function BTSelector.prototype.Reset(self)
|
||||
self.runningIndex = 0
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.children do
|
||||
self.children[i + 1]:Reset()
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
____exports.BTInverter = __TS__Class()
|
||||
local BTInverter = ____exports.BTInverter
|
||||
BTInverter.name = "BTInverter"
|
||||
function BTInverter.prototype.____constructor(self, child)
|
||||
self.child = child
|
||||
end
|
||||
function BTInverter.prototype.Tick(self, ctx)
|
||||
local st = self.child:Tick(ctx)
|
||||
if st == 0 then
|
||||
return 1
|
||||
end
|
||||
if st == 1 then
|
||||
return 0
|
||||
end
|
||||
return 2
|
||||
end
|
||||
function BTInverter.prototype.Reset(self)
|
||||
self.child:Reset()
|
||||
end
|
||||
____exports.BTCooldown = __TS__Class()
|
||||
local BTCooldown = ____exports.BTCooldown
|
||||
BTCooldown.name = "BTCooldown"
|
||||
function BTCooldown.prototype.____constructor(self, child, cooldownSeconds)
|
||||
self.lastSuccessTime = -9999
|
||||
self.child = child
|
||||
self.cooldownSeconds = cooldownSeconds
|
||||
end
|
||||
function BTCooldown.prototype.Tick(self, ctx)
|
||||
if ctx.time - self.lastSuccessTime < self.cooldownSeconds then
|
||||
return 1
|
||||
end
|
||||
local st = self.child:Tick(ctx)
|
||||
if st == 0 then
|
||||
self.lastSuccessTime = ctx.time
|
||||
end
|
||||
return st
|
||||
end
|
||||
function BTCooldown.prototype.Reset(self)
|
||||
self.child:Reset()
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,180 @@
|
||||
local ____lualib = require("lualib_bundle")
|
||||
local __TS__Class = ____lualib.__TS__Class
|
||||
local ____exports = {}
|
||||
____exports.AttributeAndBuffComponent = __TS__Class()
|
||||
local AttributeAndBuffComponent = ____exports.AttributeAndBuffComponent
|
||||
AttributeAndBuffComponent.name = "AttributeAndBuffComponent"
|
||||
function AttributeAndBuffComponent.prototype.____constructor(self, initialStats)
|
||||
self.baseStats = {}
|
||||
self.buffs = {}
|
||||
self.listeners = {}
|
||||
for k, v in pairs(initialStats) do
|
||||
self.baseStats[k] = v
|
||||
end
|
||||
end
|
||||
function AttributeAndBuffComponent.prototype.OnAttributeChanged(self, cb)
|
||||
self.listeners[#self.listeners + 1] = cb
|
||||
end
|
||||
function AttributeAndBuffComponent.prototype.GetBase(self, attr)
|
||||
return self.baseStats[attr] or 0
|
||||
end
|
||||
function AttributeAndBuffComponent.prototype.SetBase(self, attr, val)
|
||||
local clamped = val
|
||||
if attr == "HP" then
|
||||
clamped = math.max(
|
||||
0,
|
||||
math.min(
|
||||
val,
|
||||
self:GetFinal("MaxHP")
|
||||
)
|
||||
)
|
||||
end
|
||||
self.baseStats[attr] = clamped
|
||||
self:Notify(
|
||||
attr,
|
||||
self:GetFinal(attr)
|
||||
)
|
||||
end
|
||||
function AttributeAndBuffComponent.prototype.GetFinal(self, attr)
|
||||
local baseVal = self.baseStats[attr] or 0
|
||||
local flat = 0
|
||||
local pct = 0
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.buffs do
|
||||
do
|
||||
local b = self.buffs[i + 1]
|
||||
local mods = b.spec.modifiers
|
||||
if mods == nil then
|
||||
goto __continue10
|
||||
end
|
||||
do
|
||||
local j = 0
|
||||
while j < #mods do
|
||||
do
|
||||
local m = mods[j + 1]
|
||||
if m.attr ~= attr then
|
||||
goto __continue13
|
||||
end
|
||||
if m.op == 0 then
|
||||
flat = flat + m.value * b.stacks
|
||||
else
|
||||
pct = pct + m.value * b.stacks
|
||||
end
|
||||
end
|
||||
::__continue13::
|
||||
j = j + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
::__continue10::
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return (baseVal + flat) * (1 + pct)
|
||||
end
|
||||
function AttributeAndBuffComponent.prototype.ApplyBuff(self, spec)
|
||||
local policy = spec.stackPolicy or 0
|
||||
local maxStacks = spec.maxStacks or 1
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.buffs do
|
||||
local existing = self.buffs[i + 1]
|
||||
if existing.spec.id == spec.id then
|
||||
if policy == 2 then
|
||||
return
|
||||
end
|
||||
existing.remaining = spec.duration
|
||||
if policy == 1 and existing.stacks < maxStacks then
|
||||
existing.stacks = existing.stacks + 1
|
||||
end
|
||||
return
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
self.buffs[#self.buffs + 1] = {spec = spec, stacks = 1, remaining = spec.duration, tickAccumulator = 0}
|
||||
end
|
||||
function AttributeAndBuffComponent.prototype.RemoveBuff(self, buffId)
|
||||
do
|
||||
local i = #self.buffs - 1
|
||||
while i >= 0 do
|
||||
if self.buffs[i + 1].spec.id == buffId then
|
||||
table.remove(self.buffs, i + 1)
|
||||
return true
|
||||
end
|
||||
i = i - 1
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
function AttributeAndBuffComponent.prototype.GetBuffStacks(self, buffId)
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.buffs do
|
||||
if self.buffs[i + 1].spec.id == buffId then
|
||||
return self.buffs[i + 1].stacks
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return 0
|
||||
end
|
||||
function AttributeAndBuffComponent.prototype.Tick(self, dt)
|
||||
do
|
||||
local i = #self.buffs - 1
|
||||
while i >= 0 do
|
||||
local b = self.buffs[i + 1]
|
||||
b.remaining = b.remaining - dt
|
||||
if b.spec.tickInterval ~= nil and b.spec.tickInterval > 0 and b.spec.hpPerTick ~= nil then
|
||||
b.tickAccumulator = b.tickAccumulator + dt
|
||||
while b.tickAccumulator >= b.spec.tickInterval do
|
||||
b.tickAccumulator = b.tickAccumulator - b.spec.tickInterval
|
||||
local delta = b.spec.hpPerTick * b.stacks
|
||||
self:SetBase(
|
||||
"HP",
|
||||
self:GetBase("HP") + delta
|
||||
)
|
||||
end
|
||||
end
|
||||
if b.remaining <= 0 then
|
||||
table.remove(self.buffs, i + 1)
|
||||
end
|
||||
i = i - 1
|
||||
end
|
||||
end
|
||||
end
|
||||
function AttributeAndBuffComponent.prototype.ApplyDamageFrom(self, attacker, skillMultiplier, isCrit, critMultiplier)
|
||||
if critMultiplier == nil then
|
||||
critMultiplier = 1.5
|
||||
end
|
||||
local atk = attacker:GetFinal("Attack")
|
||||
local def = math.max(
|
||||
0,
|
||||
self:GetFinal("Defense")
|
||||
)
|
||||
local raw = atk * skillMultiplier * (isCrit and critMultiplier or 1)
|
||||
local mitigated = math.floor(raw * (100 / (100 + def)) + 0.5)
|
||||
local nextHp = math.max(
|
||||
0,
|
||||
self:GetBase("HP") - mitigated
|
||||
)
|
||||
self:SetBase("HP", nextHp)
|
||||
return {
|
||||
rawDamage = raw,
|
||||
mitigatedDamage = mitigated,
|
||||
isCrit = isCrit,
|
||||
targetHpAfter = nextHp,
|
||||
targetKilled = nextHp <= 0
|
||||
}
|
||||
end
|
||||
function AttributeAndBuffComponent.prototype.Notify(self, attr, val)
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.listeners do
|
||||
self.listeners[i + 1](attr, val)
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,128 @@
|
||||
local ____lualib = require("lualib_bundle")
|
||||
local __TS__Class = ____lualib.__TS__Class
|
||||
local ____exports = {}
|
||||
____exports.CoroutineTaskRunner = __TS__Class()
|
||||
local CoroutineTaskRunner = ____exports.CoroutineTaskRunner
|
||||
CoroutineTaskRunner.name = "CoroutineTaskRunner"
|
||||
function CoroutineTaskRunner.prototype.____constructor(self)
|
||||
self.nextId = 1
|
||||
self.tasks = {}
|
||||
end
|
||||
function CoroutineTaskRunner.prototype.Start(self, body, owner)
|
||||
local ____self_0, ____nextId_1 = self, "nextId"
|
||||
local ____self_nextId_2 = ____self_0[____nextId_1]
|
||||
____self_0[____nextId_1] = ____self_nextId_2 + 1
|
||||
local id = ____self_nextId_2
|
||||
local co = coroutine.create(body)
|
||||
local task = {id = id, co = co, owner = owner, cancelled = false}
|
||||
self.tasks[#self.tasks + 1] = task
|
||||
self:StepTask(task)
|
||||
return id
|
||||
end
|
||||
function CoroutineTaskRunner.prototype.Cancel(self, taskId)
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.tasks do
|
||||
if self.tasks[i + 1].id == taskId and not self.tasks[i + 1].cancelled then
|
||||
self.tasks[i + 1].cancelled = true
|
||||
return true
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
function CoroutineTaskRunner.prototype.Tick(self, dt)
|
||||
local snapshot = {}
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.tasks do
|
||||
snapshot[i + 1] = self.tasks[i + 1]
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
do
|
||||
local i = 0
|
||||
while i < #snapshot do
|
||||
do
|
||||
local task = snapshot[i + 1]
|
||||
if task.cancelled or coroutine.status(task.co) == "dead" then
|
||||
task.cancelled = true
|
||||
goto __continue12
|
||||
end
|
||||
if task.owner ~= nil and not UE.UKismetSystemLibrary.IsValid(task.owner) then
|
||||
task.cancelled = true
|
||||
goto __continue12
|
||||
end
|
||||
local cmd = task.pending
|
||||
if cmd == nil then
|
||||
self:StepTask(task)
|
||||
elseif cmd.kind == "wait_seconds" then
|
||||
cmd.remaining = cmd.remaining - dt
|
||||
if cmd.remaining <= 0 then
|
||||
task.pending = nil
|
||||
self:StepTask(task)
|
||||
end
|
||||
elseif cmd.kind == "wait_until" then
|
||||
if cmd.predicate() then
|
||||
task.pending = nil
|
||||
self:StepTask(task)
|
||||
end
|
||||
end
|
||||
end
|
||||
::__continue12::
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
do
|
||||
local i = #self.tasks - 1
|
||||
while i >= 0 do
|
||||
local t = self.tasks[i + 1]
|
||||
if t.cancelled or coroutine.status(t.co) == "dead" then
|
||||
table.remove(self.tasks, i + 1)
|
||||
end
|
||||
i = i - 1
|
||||
end
|
||||
end
|
||||
end
|
||||
function CoroutineTaskRunner.prototype.GetActiveTaskCount(self)
|
||||
local count = 0
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.tasks do
|
||||
local t = self.tasks[i + 1]
|
||||
if not t.cancelled and coroutine.status(t.co) ~= "dead" then
|
||||
count = count + 1
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return count
|
||||
end
|
||||
function CoroutineTaskRunner.prototype.StepTask(self, task)
|
||||
if task.cancelled or coroutine.status(task.co) == "dead" then
|
||||
return
|
||||
end
|
||||
local ok, yielded = coroutine.resume(task.co)
|
||||
if not ok then
|
||||
task.cancelled = true
|
||||
error("CoroutineTaskRunner error: " .. tostring(yielded))
|
||||
end
|
||||
if coroutine.status(task.co) == "dead" then
|
||||
task.cancelled = true
|
||||
elseif yielded ~= nil then
|
||||
task.pending = yielded
|
||||
end
|
||||
end
|
||||
function CoroutineTaskRunner.WaitSeconds(seconds)
|
||||
local cmd = {kind = "wait_seconds", remaining = seconds}
|
||||
coroutine.yield(cmd)
|
||||
end
|
||||
function CoroutineTaskRunner.WaitUntil(predicate)
|
||||
if predicate() then
|
||||
return
|
||||
end
|
||||
local cmd = {kind = "wait_until", predicate = predicate}
|
||||
coroutine.yield(cmd)
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,88 @@
|
||||
local ____lualib = require("lualib_bundle")
|
||||
local __TS__Class = ____lualib.__TS__Class
|
||||
local ____exports = {}
|
||||
____exports.StateMachine = __TS__Class()
|
||||
local StateMachine = ____exports.StateMachine
|
||||
StateMachine.name = "StateMachine"
|
||||
function StateMachine.prototype.____constructor(self, ctx)
|
||||
self.states = {}
|
||||
self.transitions = {}
|
||||
self.currentState = nil
|
||||
self.stateElapsed = 0
|
||||
self.paused = false
|
||||
self.history = {}
|
||||
self.ctx = ctx
|
||||
end
|
||||
function StateMachine.prototype.RegisterState(self, id, handler)
|
||||
self.states[id] = handler
|
||||
end
|
||||
function StateMachine.prototype.AddTransition(self, from, to, condition)
|
||||
self.transitions[#self.transitions + 1] = {from = from, to = to, condition = condition}
|
||||
end
|
||||
function StateMachine.prototype.Start(self, initialState)
|
||||
if self.states[initialState] == nil then
|
||||
return false
|
||||
end
|
||||
self.currentState = initialState
|
||||
self.stateElapsed = 0
|
||||
self.history[#self.history + 1] = initialState
|
||||
local handler = self.states[initialState]
|
||||
if handler and handler.OnEnter then
|
||||
handler.OnEnter(self.ctx, nil)
|
||||
end
|
||||
return true
|
||||
end
|
||||
function StateMachine.prototype.ChangeState(self, nextState)
|
||||
if self.currentState == nextState or self.states[nextState] == nil then
|
||||
return false
|
||||
end
|
||||
local prev = self.currentState
|
||||
if prev ~= nil then
|
||||
local prevHandler = self.states[prev]
|
||||
if prevHandler and prevHandler.OnExit then
|
||||
prevHandler.OnExit(self.ctx, nextState)
|
||||
end
|
||||
end
|
||||
self.currentState = nextState
|
||||
self.stateElapsed = 0
|
||||
self.history[#self.history + 1] = nextState
|
||||
local nextHandler = self.states[nextState]
|
||||
if nextHandler and nextHandler.OnEnter then
|
||||
nextHandler.OnEnter(self.ctx, prev)
|
||||
end
|
||||
return true
|
||||
end
|
||||
function StateMachine.prototype.Update(self, dt)
|
||||
if self.paused or self.currentState == nil then
|
||||
return
|
||||
end
|
||||
self.stateElapsed = self.stateElapsed + dt
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.transitions do
|
||||
local tr = self.transitions[i + 1]
|
||||
if (tr.from == "*" or tr.from == self.currentState) and tr.to ~= self.currentState and tr.condition(self.ctx) then
|
||||
self:ChangeState(tr.to)
|
||||
break
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
local handler = self.states[self.currentState]
|
||||
if handler and handler.OnUpdate then
|
||||
handler.OnUpdate(self.ctx, dt)
|
||||
end
|
||||
end
|
||||
function StateMachine.prototype.SetPaused(self, paused)
|
||||
self.paused = paused
|
||||
end
|
||||
function StateMachine.prototype.GetCurrentState(self)
|
||||
return self.currentState
|
||||
end
|
||||
function StateMachine.prototype.GetStateElapsed(self)
|
||||
return self.stateElapsed
|
||||
end
|
||||
function StateMachine.prototype.GetHistory(self)
|
||||
return self.history
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,483 @@
|
||||
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
|
||||
function ____exports.RunGameplayTests()
|
||||
Suite(
|
||||
"Gameplay.Systems",
|
||||
function()
|
||||
Test(
|
||||
"FSM: state lifecycle, conditional transitions, pause and history",
|
||||
function()
|
||||
local ctx = {speed = 0, hp = 100, log = {}}
|
||||
local fsm = __TS__New(StateMachine, ctx)
|
||||
fsm:RegisterState(
|
||||
"Idle",
|
||||
{
|
||||
OnEnter = function(c)
|
||||
c.log[#c.log + 1] = "Enter:Idle"
|
||||
end,
|
||||
OnExit = function(c)
|
||||
c.log[#c.log + 1] = "Exit:Idle"
|
||||
end
|
||||
}
|
||||
)
|
||||
fsm:RegisterState(
|
||||
"Run",
|
||||
{
|
||||
OnEnter = function(c)
|
||||
c.log[#c.log + 1] = "Enter:Run"
|
||||
end,
|
||||
OnUpdate = function(c, dt)
|
||||
c.log[#c.log + 1] = "Run:" .. tostring(math.floor(dt * 100))
|
||||
end
|
||||
}
|
||||
)
|
||||
fsm:RegisterState(
|
||||
"Dead",
|
||||
{OnEnter = function(c)
|
||||
c.log[#c.log + 1] = "Enter:Dead"
|
||||
end}
|
||||
)
|
||||
fsm:AddTransition(
|
||||
"Idle",
|
||||
"Run",
|
||||
function(c) return c.speed > 0 end
|
||||
)
|
||||
fsm:AddTransition(
|
||||
"Run",
|
||||
"Idle",
|
||||
function(c) return c.speed == 0 end
|
||||
)
|
||||
fsm:AddTransition(
|
||||
"*",
|
||||
"Dead",
|
||||
function(c) return c.hp <= 0 end
|
||||
)
|
||||
AssertTrue(fsm:Start("Idle"))
|
||||
AssertEqual(
|
||||
fsm:GetCurrentState(),
|
||||
"Idle"
|
||||
)
|
||||
ctx.speed = 300
|
||||
fsm:Update(0.1)
|
||||
AssertEqual(
|
||||
fsm:GetCurrentState(),
|
||||
"Run"
|
||||
)
|
||||
fsm:SetPaused(true)
|
||||
ctx.hp = 0
|
||||
fsm:Update(0.1)
|
||||
AssertEqual(
|
||||
fsm:GetCurrentState(),
|
||||
"Run"
|
||||
)
|
||||
fsm:SetPaused(false)
|
||||
fsm:Update(0.1)
|
||||
AssertEqual(
|
||||
fsm:GetCurrentState(),
|
||||
"Dead"
|
||||
)
|
||||
AssertArrayEqual(
|
||||
fsm:GetHistory(),
|
||||
{"Idle", "Run", "Dead"}
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"ObjectPool: prewarm, acquire/reuse, maxCapacity cap and reset hooks",
|
||||
function()
|
||||
local pool = __TS__New(
|
||||
ObjectPool,
|
||||
{
|
||||
factory = function() return {active = false, damage = 0} end,
|
||||
onAcquire = function(b)
|
||||
b.active = true
|
||||
b.damage = 10
|
||||
end,
|
||||
onRelease = function(b)
|
||||
b.active = false
|
||||
b.damage = 0
|
||||
end,
|
||||
maxCapacity = 2
|
||||
}
|
||||
)
|
||||
pool:Prewarm(2)
|
||||
AssertEqual(
|
||||
pool:GetIdleCount(),
|
||||
2
|
||||
)
|
||||
AssertEqual(
|
||||
pool:GetTotalCreated(),
|
||||
2
|
||||
)
|
||||
local b1 = pool:Acquire()
|
||||
local b2 = pool:Acquire()
|
||||
local b3 = pool:Acquire()
|
||||
AssertTrue(b1.active)
|
||||
AssertEqual(b1.damage, 10)
|
||||
AssertEqual(
|
||||
pool:GetActiveCount(),
|
||||
3
|
||||
)
|
||||
AssertEqual(
|
||||
pool:GetTotalCreated(),
|
||||
3
|
||||
)
|
||||
pool:Release(b1)
|
||||
pool:Release(b2)
|
||||
pool:Release(b3)
|
||||
AssertFalse(b1.active)
|
||||
AssertEqual(
|
||||
pool:GetActiveCount(),
|
||||
0
|
||||
)
|
||||
AssertEqual(
|
||||
pool:GetIdleCount(),
|
||||
2
|
||||
)
|
||||
local reused = pool:Acquire()
|
||||
AssertEqual(
|
||||
pool:GetTotalCreated(),
|
||||
3
|
||||
)
|
||||
AssertTrue(reused.active)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"TimerScheduler & CooldownTracker: one-shot, repeat, self-cancel, timeScale and cooldowns",
|
||||
function()
|
||||
local scheduler = __TS__New(TimerScheduler)
|
||||
local events = {}
|
||||
scheduler:ScheduleOnce(
|
||||
0.5,
|
||||
function()
|
||||
events[#events + 1] = "once"
|
||||
end
|
||||
)
|
||||
local repId = scheduler:ScheduleRepeat(
|
||||
0.25,
|
||||
function(id)
|
||||
events[#events + 1] = "rep#" .. tostring(id)
|
||||
end,
|
||||
3
|
||||
)
|
||||
local selfCancelCount = 0
|
||||
scheduler:ScheduleRepeat(
|
||||
0.2,
|
||||
function(id)
|
||||
selfCancelCount = selfCancelCount + 1
|
||||
if selfCancelCount == 2 then
|
||||
scheduler:Cancel(id)
|
||||
end
|
||||
end
|
||||
)
|
||||
scheduler:Tick(0.5)
|
||||
AssertEqual(selfCancelCount, 2)
|
||||
AssertEqual(#events, 3)
|
||||
scheduler:SetPaused(repId, true)
|
||||
scheduler:Tick(1)
|
||||
AssertEqual(#events, 3)
|
||||
scheduler:SetPaused(repId, false)
|
||||
scheduler:SetTimeScale(0.5)
|
||||
scheduler:Tick(0.5)
|
||||
AssertEqual(#events, 4)
|
||||
AssertEqual(
|
||||
scheduler:GetActiveCount(),
|
||||
0
|
||||
)
|
||||
local cd = __TS__New(CooldownTracker)
|
||||
AssertTrue(cd:IsReady("Fireball"))
|
||||
cd:StartCooldown("Fireball", 5)
|
||||
AssertFalse(cd:IsReady("Fireball"))
|
||||
cd:Tick(2)
|
||||
AssertNear(
|
||||
cd:GetRemaining("Fireball"),
|
||||
3
|
||||
)
|
||||
cd:ReduceCooldown("Fireball", 3.5)
|
||||
AssertTrue(cd:IsReady("Fireball"))
|
||||
AssertEqual(
|
||||
cd:GetRemaining("Fireball"),
|
||||
0
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"BuffAndAttributeSystem: flat/percent modifiers, stacking, DoT tick and damage mitigation",
|
||||
function()
|
||||
local hero = __TS__New(AttributeAndBuffComponent, {MaxHP = 200, HP = 200, Attack = 50, Defense = 0})
|
||||
local boss = __TS__New(AttributeAndBuffComponent, {MaxHP = 500, HP = 500, Attack = 40, Defense = 100})
|
||||
local furyBuff = {
|
||||
id = "Fury",
|
||||
duration = 5,
|
||||
maxStacks = 3,
|
||||
stackPolicy = 1,
|
||||
modifiers = {{attr = "Attack", op = 0, value = 10}, {attr = "Attack", op = 1, value = 0.2}}
|
||||
}
|
||||
hero:ApplyBuff(furyBuff)
|
||||
hero:ApplyBuff(furyBuff)
|
||||
AssertEqual(
|
||||
hero:GetBuffStacks("Fury"),
|
||||
2
|
||||
)
|
||||
AssertNear(
|
||||
hero:GetFinal("Attack"),
|
||||
98
|
||||
)
|
||||
local dmg = boss:ApplyDamageFrom(hero, 1, true, 1.5)
|
||||
AssertEqual(dmg.mitigatedDamage, 74)
|
||||
AssertEqual(dmg.targetHpAfter, 426)
|
||||
AssertFalse(dmg.targetKilled)
|
||||
boss:ApplyBuff({id = "Poison", duration = 3.1, tickInterval = 1, hpPerTick = -15})
|
||||
boss:Tick(2.5)
|
||||
AssertEqual(
|
||||
boss:GetBase("HP"),
|
||||
396
|
||||
)
|
||||
boss:Tick(1)
|
||||
AssertEqual(
|
||||
boss:GetBase("HP"),
|
||||
381
|
||||
)
|
||||
AssertEqual(
|
||||
boss:GetBuffStacks("Poison"),
|
||||
0
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"InventorySystem: stack merge, split, swap, consume, filter and serialize/deserialize",
|
||||
function()
|
||||
local inv = __TS__New(InventorySystem, 4)
|
||||
inv:RegisterItemDef({
|
||||
itemId = "potion_hp",
|
||||
name = "Health Potion",
|
||||
category = "Consumable",
|
||||
rarity = 0,
|
||||
maxStack = 10
|
||||
})
|
||||
inv:RegisterItemDef({
|
||||
itemId = "sword_excalibur",
|
||||
name = "Excalibur",
|
||||
category = "Weapon",
|
||||
rarity = 3,
|
||||
maxStack = 1
|
||||
})
|
||||
AssertEqual(
|
||||
inv:AddItem("potion_hp", 25),
|
||||
0
|
||||
)
|
||||
AssertEqual(
|
||||
inv:GetItemCount("potion_hp"),
|
||||
25
|
||||
)
|
||||
AssertEqual(
|
||||
inv:GetUsedSlotCount(),
|
||||
3
|
||||
)
|
||||
AssertEqual(
|
||||
inv:AddItem("sword_excalibur", 2),
|
||||
1
|
||||
)
|
||||
AssertEqual(
|
||||
inv:GetItemCount("sword_excalibur"),
|
||||
1
|
||||
)
|
||||
AssertTrue(inv:ConsumeItem("potion_hp", 12))
|
||||
AssertEqual(
|
||||
inv:GetItemCount("potion_hp"),
|
||||
13
|
||||
)
|
||||
AssertNil(inv:GetSlot(2))
|
||||
AssertTrue(inv:SplitSlot(0, 2, 4))
|
||||
AssertEqual(
|
||||
inv:GetSlot(0).count,
|
||||
6
|
||||
)
|
||||
AssertEqual(
|
||||
inv:GetSlot(2).count,
|
||||
4
|
||||
)
|
||||
AssertTrue(inv:SwapSlots(0, 3))
|
||||
AssertEqual(
|
||||
inv:GetSlot(0).itemId,
|
||||
"sword_excalibur"
|
||||
)
|
||||
AssertEqual(
|
||||
#inv:FilterByCategory("Weapon"),
|
||||
1
|
||||
)
|
||||
AssertEqual(
|
||||
#inv:FilterByCategory("Consumable"),
|
||||
3
|
||||
)
|
||||
local saved = inv:Serialize()
|
||||
local restored = __TS__New(InventorySystem, 1)
|
||||
restored:Deserialize(saved)
|
||||
AssertEqual(
|
||||
restored:GetItemCount("potion_hp"),
|
||||
13
|
||||
)
|
||||
AssertEqual(
|
||||
restored:GetSlot(0).itemId,
|
||||
"sword_excalibur"
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"CoroutineTaskRunner: WaitSeconds, WaitUntil and UObject destroy auto-cancellation",
|
||||
function()
|
||||
local runner = __TS__New(CoroutineTaskRunner)
|
||||
local trace = {}
|
||||
local doorOpened = false
|
||||
runner:Start(function()
|
||||
trace[#trace + 1] = "start"
|
||||
CoroutineTaskRunner.WaitSeconds(0.5)
|
||||
trace[#trace + 1] = "after_delay"
|
||||
CoroutineTaskRunner.WaitUntil(function() return doorOpened end)
|
||||
trace[#trace + 1] = "entered_room"
|
||||
end)
|
||||
AssertArrayEqual(trace, {"start"})
|
||||
runner:Tick(0.3)
|
||||
AssertArrayEqual(trace, {"start"})
|
||||
runner:Tick(0.3)
|
||||
AssertArrayEqual(trace, {"start", "after_delay"})
|
||||
runner:Tick(1)
|
||||
AssertArrayEqual(trace, {"start", "after_delay"})
|
||||
doorOpened = true
|
||||
runner:Tick(0.016)
|
||||
AssertArrayEqual(trace, {"start", "after_delay", "entered_room"})
|
||||
AssertEqual(
|
||||
runner:GetActiveTaskCount(),
|
||||
0
|
||||
)
|
||||
local ownerActor = CreateBoundInstance({}, "AActor")
|
||||
local postDestroyExecuted = false
|
||||
runner:Start(
|
||||
function()
|
||||
CoroutineTaskRunner.WaitSeconds(1)
|
||||
postDestroyExecuted = true
|
||||
end,
|
||||
ownerActor
|
||||
)
|
||||
ownerActor:K2_DestroyActor()
|
||||
runner:Tick(2)
|
||||
AssertFalse(postDestroyExecuted)
|
||||
AssertEqual(
|
||||
runner:GetActiveTaskCount(),
|
||||
0
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"BehaviorTree: Selector/Sequence/Cooldown/Inverter with Running resumption",
|
||||
function()
|
||||
local log = {}
|
||||
local castProgress = 0
|
||||
local castUltimate = __TS__New(
|
||||
BTCooldown,
|
||||
__TS__New(
|
||||
BTSequence,
|
||||
{
|
||||
__TS__New(
|
||||
BTCondition,
|
||||
function(ctx) return ctx.bb.mana >= 50 end
|
||||
),
|
||||
__TS__New(
|
||||
BTAction,
|
||||
function(ctx)
|
||||
castProgress = castProgress + ctx.dt
|
||||
if castProgress < 1 then
|
||||
log[#log + 1] = "casting"
|
||||
return 2
|
||||
end
|
||||
castProgress = 0
|
||||
ctx.bb.mana = ctx.bb.mana - 50
|
||||
log[#log + 1] = "ult_fired"
|
||||
return 0
|
||||
end
|
||||
)
|
||||
}
|
||||
),
|
||||
5
|
||||
)
|
||||
local basicAttack = __TS__New(
|
||||
BTSequence,
|
||||
{
|
||||
__TS__New(
|
||||
BTInverter,
|
||||
__TS__New(
|
||||
BTCondition,
|
||||
function(ctx) return ctx.bb.stunned == true end
|
||||
)
|
||||
),
|
||||
__TS__New(
|
||||
BTAction,
|
||||
function()
|
||||
log[#log + 1] = "basic_attack"
|
||||
return 0
|
||||
end
|
||||
)
|
||||
}
|
||||
)
|
||||
local root = __TS__New(BTSelector, {castUltimate, basicAttack})
|
||||
local ctx = {dt = 0.5, time = 0, bb = {mana = 60, stunned = false}}
|
||||
AssertEqual(
|
||||
root:Tick(ctx),
|
||||
2
|
||||
)
|
||||
ctx.time = 0.5
|
||||
AssertEqual(
|
||||
root:Tick(ctx),
|
||||
0
|
||||
)
|
||||
AssertEqual(ctx.bb.mana, 10)
|
||||
ctx.time = 1
|
||||
AssertEqual(
|
||||
root:Tick(ctx),
|
||||
0
|
||||
)
|
||||
ctx.time = 1.5
|
||||
ctx.bb.stunned = true
|
||||
AssertEqual(
|
||||
root:Tick(ctx),
|
||||
1
|
||||
)
|
||||
AssertArrayEqual(log, {"casting", "ult_fired", "basic_attack"})
|
||||
end
|
||||
)
|
||||
end
|
||||
)
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,161 @@
|
||||
local ____lualib = require("lualib_bundle")
|
||||
local __TS__Class = ____lualib.__TS__Class
|
||||
local ____exports = {}
|
||||
____exports.InventorySystem = __TS__Class()
|
||||
local InventorySystem = ____exports.InventorySystem
|
||||
InventorySystem.name = "InventorySystem"
|
||||
function InventorySystem.prototype.____constructor(self, capacity)
|
||||
self.defs = {}
|
||||
self.slots = {}
|
||||
self.capacity = capacity
|
||||
end
|
||||
function InventorySystem.prototype.RegisterItemDef(self, def)
|
||||
self.defs[def.itemId] = def
|
||||
end
|
||||
function InventorySystem.prototype.AddItem(self, itemId, amount)
|
||||
local def = self.defs[itemId]
|
||||
if def == nil or amount <= 0 then
|
||||
return amount
|
||||
end
|
||||
local remaining = amount
|
||||
do
|
||||
local i = 0
|
||||
while i < self.capacity and remaining > 0 do
|
||||
local slot = self.slots[i]
|
||||
if slot ~= nil and slot.itemId == itemId and slot.count < def.maxStack then
|
||||
local space = def.maxStack - slot.count
|
||||
local add = math.min(space, remaining)
|
||||
slot.count = slot.count + add
|
||||
remaining = remaining - add
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
do
|
||||
local i = 0
|
||||
while i < self.capacity and remaining > 0 do
|
||||
if self.slots[i] == nil then
|
||||
local add = math.min(def.maxStack, remaining)
|
||||
self.slots[i] = {itemId = itemId, count = add}
|
||||
remaining = remaining - add
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return remaining
|
||||
end
|
||||
function InventorySystem.prototype.ConsumeItem(self, itemId, amount)
|
||||
if amount <= 0 or self:GetItemCount(itemId) < amount then
|
||||
return false
|
||||
end
|
||||
local remaining = amount
|
||||
do
|
||||
local i = self.capacity - 1
|
||||
while i >= 0 and remaining > 0 do
|
||||
local slot = self.slots[i]
|
||||
if slot ~= nil and slot.itemId == itemId then
|
||||
local take = math.min(slot.count, remaining)
|
||||
slot.count = slot.count - take
|
||||
remaining = remaining - take
|
||||
if slot.count <= 0 then
|
||||
self.slots[i] = nil
|
||||
end
|
||||
end
|
||||
i = i - 1
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
function InventorySystem.prototype.SwapSlots(self, slotA, slotB)
|
||||
if slotA < 0 or slotA >= self.capacity or slotB < 0 or slotB >= self.capacity then
|
||||
return false
|
||||
end
|
||||
local tmp = self.slots[slotA]
|
||||
self.slots[slotA] = self.slots[slotB]
|
||||
self.slots[slotB] = tmp
|
||||
return true
|
||||
end
|
||||
function InventorySystem.prototype.SplitSlot(self, fromSlot, toSlot, splitCount)
|
||||
if fromSlot < 0 or fromSlot >= self.capacity or toSlot < 0 or toSlot >= self.capacity or fromSlot == toSlot then
|
||||
return false
|
||||
end
|
||||
local src = self.slots[fromSlot]
|
||||
if src == nil or self.slots[toSlot] ~= nil then
|
||||
return false
|
||||
end
|
||||
if splitCount <= 0 or splitCount >= src.count then
|
||||
return false
|
||||
end
|
||||
src.count = src.count - splitCount
|
||||
self.slots[toSlot] = {itemId = src.itemId, count = splitCount}
|
||||
return true
|
||||
end
|
||||
function InventorySystem.prototype.GetItemCount(self, itemId)
|
||||
local total = 0
|
||||
do
|
||||
local i = 0
|
||||
while i < self.capacity do
|
||||
local slot = self.slots[i]
|
||||
if slot ~= nil and slot.itemId == itemId then
|
||||
total = total + slot.count
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return total
|
||||
end
|
||||
function InventorySystem.prototype.GetSlot(self, index)
|
||||
return self.slots[index]
|
||||
end
|
||||
function InventorySystem.prototype.GetUsedSlotCount(self)
|
||||
local used = 0
|
||||
do
|
||||
local i = 0
|
||||
while i < self.capacity do
|
||||
if self.slots[i] ~= nil then
|
||||
used = used + 1
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return used
|
||||
end
|
||||
function InventorySystem.prototype.FilterByCategory(self, category)
|
||||
local out = {}
|
||||
do
|
||||
local i = 0
|
||||
while i < self.capacity do
|
||||
local slot = self.slots[i]
|
||||
if slot ~= nil then
|
||||
local def = self.defs[slot.itemId]
|
||||
if def ~= nil and def.category == category then
|
||||
out[#out + 1] = slot
|
||||
end
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
function InventorySystem.prototype.Serialize(self)
|
||||
local copiedSlots = {}
|
||||
do
|
||||
local i = 0
|
||||
while i < self.capacity do
|
||||
local s = self.slots[i]
|
||||
if s ~= nil then
|
||||
copiedSlots[i] = {itemId = s.itemId, count = s.count}
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return {capacity = self.capacity, slots = copiedSlots}
|
||||
end
|
||||
function InventorySystem.prototype.Deserialize(self, data)
|
||||
self.capacity = data.capacity
|
||||
self.slots = {}
|
||||
for idx, s in pairs(data.slots) do
|
||||
self.slots[idx] = {itemId = s.itemId, count = s.count}
|
||||
end
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,61 @@
|
||||
local ____lualib = require("lualib_bundle")
|
||||
local __TS__Class = ____lualib.__TS__Class
|
||||
local ____exports = {}
|
||||
____exports.ObjectPool = __TS__Class()
|
||||
local ObjectPool = ____exports.ObjectPool
|
||||
ObjectPool.name = "ObjectPool"
|
||||
function ObjectPool.prototype.____constructor(self, options)
|
||||
self.idle = {}
|
||||
self.activeCount = 0
|
||||
self.totalCreated = 0
|
||||
self.factory = options.factory
|
||||
self.onAcquire = options.onAcquire
|
||||
self.onRelease = options.onRelease
|
||||
self.maxCapacity = options.maxCapacity or 64
|
||||
end
|
||||
function ObjectPool.prototype.Prewarm(self, count)
|
||||
local target = math.min(count, self.maxCapacity)
|
||||
while #self.idle < target do
|
||||
self.totalCreated = self.totalCreated + 1
|
||||
self.idle[#self.idle + 1] = self.factory()
|
||||
end
|
||||
end
|
||||
function ObjectPool.prototype.Acquire(self)
|
||||
local obj
|
||||
if #self.idle > 0 then
|
||||
obj = table.remove(self.idle)
|
||||
else
|
||||
self.totalCreated = self.totalCreated + 1
|
||||
obj = self.factory()
|
||||
end
|
||||
self.activeCount = self.activeCount + 1
|
||||
if self.onAcquire then
|
||||
self.onAcquire(obj)
|
||||
end
|
||||
return obj
|
||||
end
|
||||
function ObjectPool.prototype.Release(self, obj)
|
||||
if self.activeCount > 0 then
|
||||
self.activeCount = self.activeCount - 1
|
||||
end
|
||||
if self.onRelease then
|
||||
self.onRelease(obj)
|
||||
end
|
||||
if #self.idle < self.maxCapacity then
|
||||
self.idle[#self.idle + 1] = obj
|
||||
end
|
||||
end
|
||||
function ObjectPool.prototype.Clear(self)
|
||||
self.idle = {}
|
||||
self.activeCount = 0
|
||||
end
|
||||
function ObjectPool.prototype.GetIdleCount(self)
|
||||
return #self.idle
|
||||
end
|
||||
function ObjectPool.prototype.GetActiveCount(self)
|
||||
return self.activeCount
|
||||
end
|
||||
function ObjectPool.prototype.GetTotalCreated(self)
|
||||
return self.totalCreated
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,159 @@
|
||||
local ____lualib = require("lualib_bundle")
|
||||
local __TS__Class = ____lualib.__TS__Class
|
||||
local ____exports = {}
|
||||
____exports.TimerScheduler = __TS__Class()
|
||||
local TimerScheduler = ____exports.TimerScheduler
|
||||
TimerScheduler.name = "TimerScheduler"
|
||||
function TimerScheduler.prototype.____constructor(self)
|
||||
self.nextId = 1
|
||||
self.timers = {}
|
||||
self.timeScale = 1
|
||||
end
|
||||
function TimerScheduler.prototype.ScheduleOnce(self, delay, callback)
|
||||
return self:AddTimer(delay, 1, callback)
|
||||
end
|
||||
function TimerScheduler.prototype.ScheduleRepeat(self, interval, callback, maxRepeats)
|
||||
if maxRepeats == nil then
|
||||
maxRepeats = 0
|
||||
end
|
||||
return self:AddTimer(interval, maxRepeats, callback)
|
||||
end
|
||||
function TimerScheduler.prototype.AddTimer(self, interval, maxRepeats, callback)
|
||||
local ____self_0, ____nextId_1 = self, "nextId"
|
||||
local ____self_nextId_2 = ____self_0[____nextId_1]
|
||||
____self_0[____nextId_1] = ____self_nextId_2 + 1
|
||||
local id = ____self_nextId_2
|
||||
local safeInterval = math.max(0.0001, interval)
|
||||
self.timers[#self.timers + 1] = {
|
||||
id = id,
|
||||
interval = safeInterval,
|
||||
remaining = safeInterval,
|
||||
maxRepeats = maxRepeats,
|
||||
firedCount = 0,
|
||||
paused = false,
|
||||
cancelled = false,
|
||||
callback = callback
|
||||
}
|
||||
return id
|
||||
end
|
||||
function TimerScheduler.prototype.Cancel(self, handleId)
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.timers do
|
||||
if self.timers[i + 1].id == handleId and not self.timers[i + 1].cancelled then
|
||||
self.timers[i + 1].cancelled = true
|
||||
return true
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
function TimerScheduler.prototype.SetPaused(self, handleId, paused)
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.timers do
|
||||
if self.timers[i + 1].id == handleId then
|
||||
self.timers[i + 1].paused = paused
|
||||
return
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
function TimerScheduler.prototype.SetTimeScale(self, scale)
|
||||
self.timeScale = math.max(0, scale)
|
||||
end
|
||||
function TimerScheduler.prototype.Tick(self, dt)
|
||||
local scaledDt = dt * self.timeScale
|
||||
if scaledDt <= 0 then
|
||||
return
|
||||
end
|
||||
local snapshot = {}
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.timers do
|
||||
snapshot[i + 1] = self.timers[i + 1]
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
do
|
||||
local i = 0
|
||||
while i < #snapshot do
|
||||
do
|
||||
local t = snapshot[i + 1]
|
||||
if t.cancelled or t.paused then
|
||||
goto __continue20
|
||||
end
|
||||
t.remaining = t.remaining - scaledDt
|
||||
while not t.cancelled and not t.paused and t.remaining <= 0 do
|
||||
t.firedCount = t.firedCount + 1
|
||||
t.callback(t.id)
|
||||
if t.maxRepeats > 0 and t.firedCount >= t.maxRepeats then
|
||||
t.cancelled = true
|
||||
break
|
||||
end
|
||||
t.remaining = t.remaining + t.interval
|
||||
end
|
||||
end
|
||||
::__continue20::
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
do
|
||||
local i = #self.timers - 1
|
||||
while i >= 0 do
|
||||
if self.timers[i + 1].cancelled then
|
||||
table.remove(self.timers, i + 1)
|
||||
end
|
||||
i = i - 1
|
||||
end
|
||||
end
|
||||
end
|
||||
function TimerScheduler.prototype.GetActiveCount(self)
|
||||
local count = 0
|
||||
do
|
||||
local i = 0
|
||||
while i < #self.timers do
|
||||
if not self.timers[i + 1].cancelled then
|
||||
count = count + 1
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return count
|
||||
end
|
||||
____exports.CooldownTracker = __TS__Class()
|
||||
local CooldownTracker = ____exports.CooldownTracker
|
||||
CooldownTracker.name = "CooldownTracker"
|
||||
function CooldownTracker.prototype.____constructor(self)
|
||||
self.remainingMap = {}
|
||||
end
|
||||
function CooldownTracker.prototype.StartCooldown(self, skillId, duration)
|
||||
if duration > 0 then
|
||||
self.remainingMap[skillId] = duration
|
||||
end
|
||||
end
|
||||
function CooldownTracker.prototype.IsReady(self, skillId)
|
||||
local rem = self.remainingMap[skillId]
|
||||
return rem == nil or rem <= 0
|
||||
end
|
||||
function CooldownTracker.prototype.GetRemaining(self, skillId)
|
||||
return self.remainingMap[skillId] or 0
|
||||
end
|
||||
function CooldownTracker.prototype.ReduceCooldown(self, skillId, seconds)
|
||||
local rem = self.remainingMap[skillId]
|
||||
if rem ~= nil then
|
||||
local next = rem - seconds
|
||||
self.remainingMap[skillId] = next > 0 and next or nil
|
||||
end
|
||||
end
|
||||
function CooldownTracker.prototype.Tick(self, dt)
|
||||
for skillId, rem in pairs(self.remainingMap) do
|
||||
if rem ~= nil then
|
||||
local next = rem - dt
|
||||
self.remainingMap[skillId] = next > 0 and next or nil
|
||||
end
|
||||
end
|
||||
end
|
||||
return ____exports
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,152 @@
|
||||
local ____exports = {}
|
||||
local currentSuite = "Default"
|
||||
local results = {}
|
||||
function ____exports.Reset()
|
||||
currentSuite = "Default"
|
||||
results = {}
|
||||
end
|
||||
function ____exports.Suite(name, body)
|
||||
local prev = currentSuite
|
||||
currentSuite = name
|
||||
body()
|
||||
currentSuite = prev
|
||||
end
|
||||
function ____exports.Test(name, fn)
|
||||
local ok, err = pcall(fn)
|
||||
if ok then
|
||||
results[#results + 1] = {suite = currentSuite, name = name, passed = true}
|
||||
else
|
||||
results[#results + 1] = {
|
||||
suite = currentSuite,
|
||||
name = name,
|
||||
passed = false,
|
||||
errorMessage = tostring(err)
|
||||
}
|
||||
end
|
||||
end
|
||||
function ____exports.AssertTrue(cond, msg)
|
||||
if not cond then
|
||||
error(msg or "Expected condition to be truthy", 2)
|
||||
end
|
||||
end
|
||||
function ____exports.AssertFalse(cond, msg)
|
||||
if cond then
|
||||
error(msg or "Expected condition to be falsy", 2)
|
||||
end
|
||||
end
|
||||
function ____exports.AssertEqual(actual, expected, msg)
|
||||
if actual ~= expected then
|
||||
local prefix = msg and msg .. ": " or ""
|
||||
error(
|
||||
string.format(
|
||||
"%sExpected %s, got %s",
|
||||
prefix,
|
||||
tostring(expected),
|
||||
tostring(actual)
|
||||
),
|
||||
2
|
||||
)
|
||||
end
|
||||
end
|
||||
function ____exports.AssertNear(actual, expected, epsilon, msg)
|
||||
if epsilon == nil then
|
||||
epsilon = 0.0001
|
||||
end
|
||||
if math.abs(actual - expected) > epsilon then
|
||||
local prefix = msg and msg .. ": " or ""
|
||||
error(
|
||||
string.format(
|
||||
"%sExpected %.6f (±%.6f), got %.6f",
|
||||
prefix,
|
||||
expected,
|
||||
epsilon,
|
||||
actual
|
||||
),
|
||||
2
|
||||
)
|
||||
end
|
||||
end
|
||||
function ____exports.AssertNil(value, msg)
|
||||
if value ~= nil then
|
||||
local prefix = msg and msg .. ": " or ""
|
||||
error(
|
||||
string.format(
|
||||
"%sExpected nil, got %s",
|
||||
prefix,
|
||||
tostring(value)
|
||||
),
|
||||
2
|
||||
)
|
||||
end
|
||||
end
|
||||
function ____exports.AssertNotNil(value, msg)
|
||||
if value == nil then
|
||||
error(msg or "Expected non-nil value", 2)
|
||||
end
|
||||
end
|
||||
function ____exports.AssertArrayEqual(actual, expected, msg)
|
||||
local prefix = msg and msg .. ": " or ""
|
||||
if #actual ~= #expected then
|
||||
error(
|
||||
string.format("%sArray length mismatch: expected %d, got %d", prefix, #expected, #actual),
|
||||
2
|
||||
)
|
||||
end
|
||||
do
|
||||
local i = 0
|
||||
while i < #expected do
|
||||
if actual[i + 1] ~= expected[i + 1] then
|
||||
error(
|
||||
string.format(
|
||||
"%sArray element [%d] mismatch: expected %s, got %s",
|
||||
prefix,
|
||||
i,
|
||||
tostring(expected[i + 1]),
|
||||
tostring(actual[i + 1])
|
||||
),
|
||||
2
|
||||
)
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
function ____exports.GetSummary()
|
||||
local passed = 0
|
||||
local failed = 0
|
||||
do
|
||||
local i = 0
|
||||
while i < #results do
|
||||
if results[i + 1].passed then
|
||||
passed = passed + 1
|
||||
else
|
||||
failed = failed + 1
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return {total = #results, passed = passed, failed = failed, results = results}
|
||||
end
|
||||
function ____exports.PrintReport()
|
||||
local summary = ____exports.GetSummary()
|
||||
local lastSuite = ""
|
||||
do
|
||||
local i = 0
|
||||
while i < #summary.results do
|
||||
local r = summary.results[i + 1]
|
||||
if r.suite ~= lastSuite then
|
||||
lastSuite = r.suite
|
||||
print(string.format("\n[%s]", r.suite))
|
||||
end
|
||||
if r.passed then
|
||||
print(string.format(" PASS %s", r.name))
|
||||
else
|
||||
print(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))
|
||||
return summary
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,46 @@
|
||||
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
|
||||
function ____exports.RunAll()
|
||||
InstallIfNeeded()
|
||||
Reset()
|
||||
RunBasicTypesAndControlFlowTests()
|
||||
RunFunctionsClosuresAndTuplesTests()
|
||||
RunPureClassesAndGenericsTests()
|
||||
RunUnLuaSyntaxTests()
|
||||
RunUnLuaExamplesTests()
|
||||
RunGameplayTests()
|
||||
RunHotReloadAndFrameworkTests()
|
||||
RunLua54PitfallsTests()
|
||||
RunLifecycleAndMemoryTests()
|
||||
return PrintReport()
|
||||
end
|
||||
local g = _G
|
||||
if g.__TS2LUA_TEST_AUTO_RUN__ == true then
|
||||
local summary = ____exports.RunAll()
|
||||
if summary.failed > 0 then
|
||||
os.exit(1)
|
||||
end
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,249 @@
|
||||
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 function EvaluateCommand(action)
|
||||
repeat
|
||||
local ____switch3 = action.kind
|
||||
local ____cond3 = ____switch3 == "move"
|
||||
if ____cond3 then
|
||||
return action.x + action.y
|
||||
end
|
||||
____cond3 = ____cond3 or ____switch3 == "damage"
|
||||
if ____cond3 then
|
||||
return action.crit and action.amount * 2 or action.amount
|
||||
end
|
||||
____cond3 = ____cond3 or ____switch3 == "noop"
|
||||
if ____cond3 then
|
||||
return 0
|
||||
end
|
||||
until true
|
||||
end
|
||||
function ____exports.RunBasicTypesAndControlFlowTests()
|
||||
Suite(
|
||||
"Syntax.BasicTypesAndControlFlow",
|
||||
function()
|
||||
Test(
|
||||
"primitives, template literals, nullish coalescing and optional chaining",
|
||||
function()
|
||||
local count = 42
|
||||
local ratio = 0.5
|
||||
local label = (("Count=" .. tostring(count)) .. ",Half=") .. tostring(math.floor(count * ratio))
|
||||
AssertEqual(label, "Count=42,Half=21")
|
||||
AssertEqual(
|
||||
tostring(count * ratio),
|
||||
"21.0"
|
||||
)
|
||||
local maybeNum = nil
|
||||
local zeroNum = 0
|
||||
local falseFlag = false
|
||||
AssertEqual(maybeNum or 99, 99)
|
||||
AssertEqual(zeroNum or 99, 0)
|
||||
local ____AssertEqual_1 = AssertEqual
|
||||
local ____falseFlag_0 = falseFlag
|
||||
if ____falseFlag_0 == nil then
|
||||
____falseFlag_0 = true
|
||||
end
|
||||
____AssertEqual_1(____falseFlag_0, false)
|
||||
local a = {}
|
||||
local b = {inner = {value = 7}}
|
||||
local ____AssertNil_4 = AssertNil
|
||||
local ____opt_2 = a.inner
|
||||
____AssertNil_4(____opt_2 and ____opt_2.value)
|
||||
local ____AssertEqual_7 = AssertEqual
|
||||
local ____opt_5 = b.inner
|
||||
____AssertEqual_7(____opt_5 and ____opt_5.value or -1, 7)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Lua 5.4 native bitwise operators and const enum inlining",
|
||||
function()
|
||||
local flags = 0
|
||||
flags = flags | 1 | 4
|
||||
AssertTrue(flags & 1 ~= 0)
|
||||
AssertFalse(flags & 2 ~= 0)
|
||||
AssertTrue(flags & 4 ~= 0)
|
||||
flags = flags & ~4
|
||||
flags = flags ~ 2
|
||||
AssertFalse(flags & 4 ~= 0)
|
||||
AssertTrue(flags & 2 ~= 0)
|
||||
AssertEqual(1 << 4, 16)
|
||||
AssertEqual((64 & 4294967295) >> 2, 16)
|
||||
local role = "Healer"
|
||||
AssertEqual(role, "Healer")
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"control flow: switch/case fallthrough, loops, continue, break, labeled loop",
|
||||
function()
|
||||
local function Classify(n)
|
||||
repeat
|
||||
local ____switch10 = n
|
||||
local ____cond10 = ____switch10 == 1 or ____switch10 == 2
|
||||
if ____cond10 then
|
||||
return "small"
|
||||
end
|
||||
____cond10 = ____cond10 or ____switch10 == 3
|
||||
if ____cond10 then
|
||||
return "medium"
|
||||
end
|
||||
do
|
||||
return "large"
|
||||
end
|
||||
until true
|
||||
end
|
||||
AssertEqual(
|
||||
Classify(1),
|
||||
"small"
|
||||
)
|
||||
AssertEqual(
|
||||
Classify(2),
|
||||
"small"
|
||||
)
|
||||
AssertEqual(
|
||||
Classify(3),
|
||||
"medium"
|
||||
)
|
||||
AssertEqual(
|
||||
Classify(9),
|
||||
"large"
|
||||
)
|
||||
local sum = 0
|
||||
local i = 0
|
||||
while i < 10 do
|
||||
do
|
||||
i = i + 1
|
||||
if i % 2 == 0 then
|
||||
goto __continue11
|
||||
end
|
||||
if i > 7 then
|
||||
break
|
||||
end
|
||||
sum = sum + i
|
||||
end
|
||||
::__continue11::
|
||||
end
|
||||
AssertEqual(sum, 16)
|
||||
local doCount = 0
|
||||
repeat
|
||||
do
|
||||
doCount = doCount + 1
|
||||
end
|
||||
until not false
|
||||
AssertEqual(doCount, 1)
|
||||
local foundPair = ""
|
||||
local found = false
|
||||
do
|
||||
local r = 0
|
||||
while r < 5 and not found do
|
||||
do
|
||||
local c = 0
|
||||
while c < 5 do
|
||||
if r * 10 + c == 23 then
|
||||
foundPair = (tostring(r) .. ",") .. tostring(c)
|
||||
found = true
|
||||
break
|
||||
end
|
||||
c = c + 1
|
||||
end
|
||||
end
|
||||
r = r + 1
|
||||
end
|
||||
end
|
||||
AssertEqual(foundPair, "2,3")
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"discriminated union narrowing and destructuring with defaults",
|
||||
function()
|
||||
AssertEqual(
|
||||
EvaluateCommand({kind = "move", x = 3, y = 4}),
|
||||
7
|
||||
)
|
||||
AssertEqual(
|
||||
EvaluateCommand({kind = "damage", amount = 25, crit = true}),
|
||||
50
|
||||
)
|
||||
AssertEqual(
|
||||
EvaluateCommand({kind = "damage", amount = 25, crit = false}),
|
||||
25
|
||||
)
|
||||
AssertEqual(
|
||||
EvaluateCommand({kind = "noop"}),
|
||||
0
|
||||
)
|
||||
local cfg = {host = "127.0.0.1"}
|
||||
local host = cfg.host
|
||||
local port = cfg.port
|
||||
if port == nil then
|
||||
port = 7777
|
||||
end
|
||||
AssertEqual(host, "127.0.0.1")
|
||||
AssertEqual(port, 7777)
|
||||
local coords = {10, 20, 30}
|
||||
local x, ____, z = table.unpack(coords, 1, 3)
|
||||
AssertEqual(x, 10)
|
||||
AssertEqual(z, 30)
|
||||
AssertNear(0.1 + 0.2, 0.3, 0.000001)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"rest parameters and spread into function calls",
|
||||
function()
|
||||
local function SumAll(...)
|
||||
local nums = {...}
|
||||
local total = 0
|
||||
do
|
||||
local idx = 0
|
||||
while idx < #nums do
|
||||
total = total + nums[idx + 1]
|
||||
idx = idx + 1
|
||||
end
|
||||
end
|
||||
return total
|
||||
end
|
||||
local data = {2, 4, 6, 8}
|
||||
AssertEqual(
|
||||
SumAll(table.unpack(data)),
|
||||
20
|
||||
)
|
||||
local ____AssertEqual_9 = AssertEqual
|
||||
local ____array_8 = __TS__SparseArrayNew(
|
||||
1,
|
||||
table.unpack(data)
|
||||
)
|
||||
__TS__SparseArrayPush(____array_8, 9)
|
||||
____AssertEqual_9(
|
||||
SumAll(__TS__SparseArraySpread(____array_8)),
|
||||
30
|
||||
)
|
||||
local ____array_10 = __TS__SparseArrayNew(
|
||||
0,
|
||||
table.unpack(data)
|
||||
)
|
||||
__TS__SparseArrayPush(____array_10, 10)
|
||||
local combined = {__TS__SparseArraySpread(____array_10)}
|
||||
AssertArrayEqual(combined, {
|
||||
0,
|
||||
2,
|
||||
4,
|
||||
6,
|
||||
8,
|
||||
10
|
||||
})
|
||||
end
|
||||
)
|
||||
end
|
||||
)
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,194 @@
|
||||
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 function DivideWithRemainder(a, b)
|
||||
if b == 0 then
|
||||
return false, 0, 0
|
||||
end
|
||||
local q = math.floor(a / b)
|
||||
local r = a % b
|
||||
return true, q, r
|
||||
end
|
||||
local function FormatId(a, b)
|
||||
if type(a) == "number" then
|
||||
return string.format("ID_%04d", a)
|
||||
end
|
||||
return string.format("%s_%04d", a, b or 0)
|
||||
end
|
||||
function ____exports.RunFunctionsClosuresAndTuplesTests()
|
||||
Suite(
|
||||
"Syntax.FunctionsClosuresAndTuples",
|
||||
function()
|
||||
Test(
|
||||
"LuaMultiReturn and $multi destructuring",
|
||||
function()
|
||||
local ok1, q1, r1 = DivideWithRemainder(17, 5)
|
||||
AssertTrue(ok1)
|
||||
AssertEqual(q1, 3)
|
||||
AssertEqual(r1, 2)
|
||||
local ok2, q2, r2 = DivideWithRemainder(10, 0)
|
||||
AssertFalse(ok2)
|
||||
AssertEqual(q2, 0)
|
||||
AssertEqual(r2, 0)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"function overloads, closures and upvalues",
|
||||
function()
|
||||
AssertEqual(
|
||||
FormatId(7),
|
||||
"ID_0007"
|
||||
)
|
||||
AssertEqual(
|
||||
FormatId("NPC", 42),
|
||||
"NPC_0042"
|
||||
)
|
||||
local function MakeAccumulator(start)
|
||||
local acc = start
|
||||
return function(delta)
|
||||
acc = acc + delta
|
||||
return acc
|
||||
end
|
||||
end
|
||||
local acc = MakeAccumulator(10)
|
||||
AssertEqual(
|
||||
acc(5),
|
||||
15
|
||||
)
|
||||
AssertEqual(
|
||||
acc(-3),
|
||||
12
|
||||
)
|
||||
AssertEqual(
|
||||
acc(8),
|
||||
20
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"explicit self colon-call vs @noSelf dot-call",
|
||||
function()
|
||||
local counter = {
|
||||
value = 10,
|
||||
Add = function(self, delta)
|
||||
self.value = self.value + delta
|
||||
return self.value
|
||||
end
|
||||
}
|
||||
AssertEqual(
|
||||
counter:Add(5),
|
||||
15
|
||||
)
|
||||
AssertEqual(
|
||||
counter:Add(7),
|
||||
22
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"TS arrays (0-based -> Lua 1-based) and table operations",
|
||||
function()
|
||||
local arr = {10, 20, 30, 40}
|
||||
AssertEqual(#arr, 4)
|
||||
AssertEqual(arr[1], 10)
|
||||
AssertEqual(arr[4], 40)
|
||||
arr[#arr + 1] = 50
|
||||
AssertEqual(#arr, 5)
|
||||
AssertEqual(
|
||||
table.remove(arr),
|
||||
50
|
||||
)
|
||||
local removed = __TS__ArraySplice(arr, 1, 2)
|
||||
AssertArrayEqual(removed, {20, 30})
|
||||
AssertArrayEqual(arr, {10, 40})
|
||||
table.insert(arr, 2, 25)
|
||||
AssertArrayEqual(arr, {10, 25, 40})
|
||||
table.remove(arr, 1)
|
||||
AssertArrayEqual(arr, {25, 40})
|
||||
local unsorted = {
|
||||
5,
|
||||
1,
|
||||
4,
|
||||
2,
|
||||
3
|
||||
}
|
||||
__TS__ArraySort(
|
||||
unsorted,
|
||||
function(____, a, b) return a - b end
|
||||
)
|
||||
AssertArrayEqual(unsorted, {
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5
|
||||
})
|
||||
AssertEqual(
|
||||
table.concat(unsorted, "-"),
|
||||
"1-2-3-4-5"
|
||||
)
|
||||
AssertEqual(
|
||||
__TS__ArrayIndexOf(unsorted, 4),
|
||||
3
|
||||
)
|
||||
AssertEqual(
|
||||
__TS__ArrayIndexOf(unsorted, 99),
|
||||
-1
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Record<K, V>, LuaTable and pairs() iteration",
|
||||
function()
|
||||
local scores = {Alice = 100, Bob = 85, Carol = 92}
|
||||
scores.Bob = nil
|
||||
local count = 0
|
||||
local total = 0
|
||||
for k, v in pairs(scores) do
|
||||
if v ~= nil then
|
||||
count = count + 1
|
||||
total = total + v
|
||||
end
|
||||
AssertTrue(k ~= "Bob")
|
||||
end
|
||||
AssertEqual(count, 2)
|
||||
AssertEqual(total, 192)
|
||||
local luaTbl = {}
|
||||
luaTbl[101] = "Sword"
|
||||
luaTbl[202] = "Shield"
|
||||
AssertEqual(luaTbl[101], "Sword")
|
||||
AssertEqual(luaTbl[202], "Shield")
|
||||
luaTbl[101] = nil
|
||||
AssertNil(luaTbl[101])
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Lua patterns (replacing forbidden JS RegExp)",
|
||||
function()
|
||||
local tag, numStr = string.match("Item_Sword_042", "^(%a+)_%a+_(%d+)$")
|
||||
AssertEqual(tag, "Item")
|
||||
AssertEqual(numStr, "042")
|
||||
local replaced, subCount = string.gsub("HP: 100, MP: 50", "%d+", "999")
|
||||
AssertEqual(replaced, "HP: 999, MP: 999")
|
||||
AssertEqual(subCount, 2)
|
||||
local tokens = {}
|
||||
for tok in string.gmatch("alpha,beta,gamma", "[^,]+") do
|
||||
tokens[#tokens + 1] = tok
|
||||
end
|
||||
AssertArrayEqual(tokens, {"alpha", "beta", "gamma"})
|
||||
end
|
||||
)
|
||||
end
|
||||
)
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,193 @@
|
||||
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()
|
||||
BaseEntity.name = "BaseEntity"
|
||||
function BaseEntity.prototype.____constructor(self, id, name)
|
||||
self.id = id
|
||||
self.name = name
|
||||
end
|
||||
function BaseEntity.prototype.GetId(self)
|
||||
return self.id
|
||||
end
|
||||
function BaseEntity.prototype.GetName(self)
|
||||
return self.name
|
||||
end
|
||||
local PureMonster = __TS__Class()
|
||||
PureMonster.name = "PureMonster"
|
||||
__TS__ClassExtends(PureMonster, BaseEntity)
|
||||
function PureMonster.prototype.____constructor(self, id, name, level)
|
||||
if level == nil then
|
||||
level = PureMonster.DefaultLevel
|
||||
end
|
||||
BaseEntity.prototype.____constructor(self, id, name)
|
||||
self.level = level
|
||||
end
|
||||
function PureMonster.prototype.GetLevel(self)
|
||||
return self.level
|
||||
end
|
||||
function PureMonster.prototype.Describe(self)
|
||||
return ((((self.name .. "#") .. tostring(self.id)) .. "(Lv.") .. tostring(self.level)) .. ")"
|
||||
end
|
||||
function PureMonster.CompareLevel(a, b)
|
||||
return a:GetLevel() - b:GetLevel()
|
||||
end
|
||||
PureMonster.DefaultLevel = 1
|
||||
local RingBuffer = __TS__Class()
|
||||
RingBuffer.name = "RingBuffer"
|
||||
function RingBuffer.prototype.____constructor(self, capacity)
|
||||
self.buffer = {}
|
||||
self.head = 0
|
||||
self.count = 0
|
||||
self.capacity = capacity
|
||||
end
|
||||
function RingBuffer.prototype.Push(self, item)
|
||||
if self.count < self.capacity then
|
||||
local idx = (self.head + self.count) % self.capacity
|
||||
self.buffer[idx + 1] = item
|
||||
self.count = self.count + 1
|
||||
else
|
||||
self.buffer[self.head + 1] = item
|
||||
self.head = (self.head + 1) % self.capacity
|
||||
end
|
||||
end
|
||||
function RingBuffer.prototype.Pop(self)
|
||||
if self.count == 0 then
|
||||
return nil
|
||||
end
|
||||
local item = self.buffer[self.head + 1]
|
||||
self.buffer[self.head + 1] = nil
|
||||
self.head = (self.head + 1) % self.capacity
|
||||
self.count = self.count - 1
|
||||
return item
|
||||
end
|
||||
function RingBuffer.prototype.GetCount(self)
|
||||
return self.count
|
||||
end
|
||||
local function FindById(list, targetId)
|
||||
do
|
||||
local i = 0
|
||||
while i < #list do
|
||||
if list[i + 1]:GetId() == targetId then
|
||||
return list[i + 1]
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local function SafeFrameworkBoundary(shouldThrow)
|
||||
do
|
||||
local function ____catch(e)
|
||||
return true, {
|
||||
false,
|
||||
tostring(e)
|
||||
}
|
||||
end
|
||||
local ____try, ____hasReturned, ____returnValue = pcall(function()
|
||||
if shouldThrow then
|
||||
error("simulated_boundary_error", 0)
|
||||
end
|
||||
return true, {true, "ok"}
|
||||
end)
|
||||
if not ____try then
|
||||
____hasReturned, ____returnValue = ____catch(____hasReturned)
|
||||
end
|
||||
if ____hasReturned then
|
||||
return table.unpack(____returnValue)
|
||||
end
|
||||
end
|
||||
end
|
||||
function ____exports.RunPureClassesAndGenericsTests()
|
||||
Suite(
|
||||
"Syntax.PureClassesAndGenerics",
|
||||
function()
|
||||
Test(
|
||||
"pure TS class inheritance, abstract methods and static helpers",
|
||||
function()
|
||||
local m1 = __TS__New(PureMonster, 1, "Slime")
|
||||
local m2 = __TS__New(PureMonster, 2, "Dragon", 50)
|
||||
AssertEqual(
|
||||
m1:GetId(),
|
||||
1
|
||||
)
|
||||
AssertEqual(
|
||||
m1:GetLevel(),
|
||||
1
|
||||
)
|
||||
AssertEqual(
|
||||
m1:Describe(),
|
||||
"Slime#1(Lv.1)"
|
||||
)
|
||||
AssertEqual(
|
||||
m2:Describe(),
|
||||
"Dragon#2(Lv.50)"
|
||||
)
|
||||
AssertTrue(PureMonster.CompareLevel(m2, m1) > 0)
|
||||
AssertTrue(__TS__InstanceOf(m1, PureMonster))
|
||||
AssertTrue(__TS__InstanceOf(m1, BaseEntity))
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"generic class RingBuffer<T> and constrained generic function",
|
||||
function()
|
||||
local rb = __TS__New(RingBuffer, 3)
|
||||
rb:Push(10)
|
||||
rb:Push(20)
|
||||
rb:Push(30)
|
||||
rb:Push(40)
|
||||
AssertEqual(
|
||||
rb:GetCount(),
|
||||
3
|
||||
)
|
||||
AssertEqual(
|
||||
rb:Pop(),
|
||||
20
|
||||
)
|
||||
AssertEqual(
|
||||
rb:Pop(),
|
||||
30
|
||||
)
|
||||
AssertEqual(
|
||||
rb:Pop(),
|
||||
40
|
||||
)
|
||||
AssertNil(rb:Pop())
|
||||
local monsters = {
|
||||
__TS__New(PureMonster, 10, "Orc", 5),
|
||||
__TS__New(PureMonster, 20, "Goblin", 2)
|
||||
}
|
||||
local found = FindById(monsters, 20)
|
||||
AssertTrue(found ~= nil)
|
||||
AssertEqual(
|
||||
found:GetName(),
|
||||
"Goblin"
|
||||
)
|
||||
AssertNil(FindById(monsters, 999))
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"@unlua-allow-try framework boundary try/catch/throw",
|
||||
function()
|
||||
local ok1, msg1 = SafeFrameworkBoundary(false)
|
||||
AssertTrue(ok1)
|
||||
AssertEqual(msg1, "ok")
|
||||
local ok2, msg2 = SafeFrameworkBoundary(true)
|
||||
AssertFalse(ok2)
|
||||
AssertTrue((string.find(msg2, "simulated_boundary_error", 1, true)) ~= nil)
|
||||
end
|
||||
)
|
||||
end
|
||||
)
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,62 @@
|
||||
local UnLuaBaseActor = UnLua.Class()
|
||||
UnLuaBaseActor.DEFAULT_HP = 100
|
||||
function UnLuaBaseActor.ReceiveBeginPlay(self)
|
||||
self.Overridden.ReceiveBeginPlay(self)
|
||||
self.hp = UnLuaBaseActor.DEFAULT_HP
|
||||
self.callTrace = {"Base.ReceiveBeginPlay"}
|
||||
end
|
||||
function UnLuaBaseActor.ApplyConfig(self, ____param_0)
|
||||
local name = ____param_0.name
|
||||
local hp = ____param_0.hp
|
||||
if hp == nil then
|
||||
hp = UnLuaBaseActor.DEFAULT_HP
|
||||
end
|
||||
self.hp = hp
|
||||
return (name .. ":") .. tostring(self.hp)
|
||||
end
|
||||
function UnLuaBaseActor.SumScores(self, ____param_1)
|
||||
local first = ____param_1[1]
|
||||
local second = ____param_1[2]
|
||||
if second == nil then
|
||||
second = 5
|
||||
end
|
||||
local rest = {}
|
||||
table.move(
|
||||
____param_1,
|
||||
3,
|
||||
#____param_1,
|
||||
1,
|
||||
rest
|
||||
)
|
||||
local sum = first + second
|
||||
do
|
||||
local i = 0
|
||||
while i < #rest do
|
||||
sum = sum + rest[i + 1]
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return sum
|
||||
end
|
||||
function UnLuaBaseActor.GetTrace(self)
|
||||
return self.callTrace
|
||||
end
|
||||
function UnLuaBaseActor.GetHp(self)
|
||||
return self.hp
|
||||
end
|
||||
function UnLuaBaseActor.ComputeBonus(self, baseVal, multiplier)
|
||||
if multiplier == nil then
|
||||
multiplier = 2
|
||||
end
|
||||
return baseVal * multiplier
|
||||
end
|
||||
function UnLuaBaseActor.StaticWithSelf(self, delta)
|
||||
return self.DEFAULT_HP + delta
|
||||
end
|
||||
function UnLuaBaseActor.StaticNoSelf(a, b)
|
||||
return a + b
|
||||
end
|
||||
function UnLuaBaseActor.StaticDocNoSelf(x)
|
||||
return x * 3
|
||||
end
|
||||
return UnLuaBaseActor
|
||||
@@ -0,0 +1,8 @@
|
||||
local UnLuaExplicitWidget = UnLua.Class("Tests.Syntax.UnLuaBaseActor")
|
||||
function UnLuaExplicitWidget.Construct(self, model)
|
||||
self.title = model.title
|
||||
end
|
||||
function UnLuaExplicitWidget.GetTitle(self)
|
||||
return self.title
|
||||
end
|
||||
return UnLuaExplicitWidget
|
||||
@@ -0,0 +1,17 @@
|
||||
local UnLuaSubActor = require("Tests.Syntax.UnLuaSubActor")
|
||||
local UnLuaGrandChildActor = UnLua.Class("Tests.Syntax.UnLuaSubActor")
|
||||
function UnLuaGrandChildActor.ReceiveBeginPlay(self)
|
||||
UnLuaSubActor.ReceiveBeginPlay(self)
|
||||
self.tier = 3
|
||||
self.callTrace[#self.callTrace + 1] = "GrandChild.ReceiveBeginPlay"
|
||||
end
|
||||
function UnLuaGrandChildActor.ComputeBonus(self, baseVal, multiplier)
|
||||
if multiplier == nil then
|
||||
multiplier = 2
|
||||
end
|
||||
return UnLuaSubActor.ComputeBonus(self, baseVal, multiplier) + self.tier
|
||||
end
|
||||
function UnLuaGrandChildActor.GetTier(self)
|
||||
return self.tier
|
||||
end
|
||||
return UnLuaGrandChildActor
|
||||
@@ -0,0 +1,21 @@
|
||||
local UnLuaBaseActor = require("Tests.Syntax.UnLuaBaseActor")
|
||||
local UnLuaSubActor = UnLua.Class("Tests.Syntax.UnLuaBaseActor")
|
||||
function UnLuaSubActor.ReceiveBeginPlay(self)
|
||||
UnLuaBaseActor.ReceiveBeginPlay(self)
|
||||
self.faction = "Ally"
|
||||
self.callTrace[#self.callTrace + 1] = "Sub.ReceiveBeginPlay"
|
||||
end
|
||||
function UnLuaSubActor.ComputeBonus(self, baseVal, multiplier)
|
||||
if multiplier == nil then
|
||||
multiplier = 2
|
||||
end
|
||||
return UnLuaBaseActor.ComputeBonus(self, baseVal, multiplier) + 10
|
||||
end
|
||||
function UnLuaSubActor.SetupWithFaction(self, cfg, faction)
|
||||
self.faction = faction
|
||||
return ((UnLuaBaseActor.ApplyConfig(self, cfg) .. "[") .. self.faction) .. "]"
|
||||
end
|
||||
function UnLuaSubActor.GetFaction(self)
|
||||
return self.faction
|
||||
end
|
||||
return UnLuaSubActor
|
||||
@@ -0,0 +1,123 @@
|
||||
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 UnLuaBaseActor = require("Tests.Syntax.UnLuaBaseActor")
|
||||
local UnLuaGrandChildActor = require("Tests.Syntax.UnLuaGrandChildActor")
|
||||
local UnLuaExplicitWidget = require("Tests.Syntax.UnLuaExplicitWidget")
|
||||
function ____exports.RunUnLuaSyntaxTests()
|
||||
Suite(
|
||||
"Syntax.UnLuaClassFeatures",
|
||||
function()
|
||||
Test(
|
||||
"@unlua base class: UnLua.Class(), self.Overridden, static methods and destructured params",
|
||||
function()
|
||||
ResetMockState()
|
||||
local actor = CreateBoundInstance(UnLuaBaseActor, "AActor")
|
||||
actor:ReceiveBeginPlay()
|
||||
AssertEqual(
|
||||
actor:GetHp(),
|
||||
100
|
||||
)
|
||||
AssertArrayEqual(
|
||||
actor:GetTrace(),
|
||||
{"Base.ReceiveBeginPlay"}
|
||||
)
|
||||
AssertArrayEqual(
|
||||
GetMockState().overriddenCalls,
|
||||
{"AActor.ReceiveBeginPlay"}
|
||||
)
|
||||
AssertEqual(
|
||||
actor:ApplyConfig({name = "Hero"}),
|
||||
"Hero:100"
|
||||
)
|
||||
AssertEqual(
|
||||
actor:ApplyConfig({name = "Boss", hp = 500}),
|
||||
"Boss:500"
|
||||
)
|
||||
AssertEqual(
|
||||
actor:SumScores({10}),
|
||||
15
|
||||
)
|
||||
AssertEqual(
|
||||
actor:SumScores({1, 2, 3, 4}),
|
||||
10
|
||||
)
|
||||
AssertEqual(
|
||||
UnLuaBaseActor:StaticWithSelf(25),
|
||||
125
|
||||
)
|
||||
AssertEqual(
|
||||
UnLuaBaseActor.StaticNoSelf(7, 8),
|
||||
15
|
||||
)
|
||||
AssertEqual(
|
||||
UnLuaBaseActor.StaticDocNoSelf(9),
|
||||
27
|
||||
)
|
||||
AssertTrue(actor:IsA(UE.AActor.StaticClass()))
|
||||
AssertTrue(UE.UKismetSystemLibrary.IsValid(actor))
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"@unlua 3-level inheritance (GrandChild -> Sub -> Base) avoids self.Super infinite recursion",
|
||||
function()
|
||||
ResetMockState()
|
||||
local grand = CreateBoundInstance(UnLuaGrandChildActor, "AActor")
|
||||
grand:ReceiveBeginPlay()
|
||||
AssertArrayEqual(
|
||||
grand:GetTrace(),
|
||||
{"Base.ReceiveBeginPlay", "Sub.ReceiveBeginPlay", "GrandChild.ReceiveBeginPlay"}
|
||||
)
|
||||
AssertArrayEqual(
|
||||
GetMockState().overriddenCalls,
|
||||
{"AActor.ReceiveBeginPlay"}
|
||||
)
|
||||
AssertEqual(
|
||||
grand:GetFaction(),
|
||||
"Ally"
|
||||
)
|
||||
AssertEqual(
|
||||
grand:GetTier(),
|
||||
3
|
||||
)
|
||||
AssertEqual(
|
||||
grand:ComputeBonus(10),
|
||||
33
|
||||
)
|
||||
AssertEqual(
|
||||
grand:ComputeBonus(10, 4),
|
||||
53
|
||||
)
|
||||
local summary = grand:SetupWithFaction({name = "Knight", hp = 250}, "Enemy")
|
||||
AssertEqual(summary, "Knight:250[Enemy]")
|
||||
AssertEqual(
|
||||
grand:GetFaction(),
|
||||
"Enemy"
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"@unlua explicit base path class without extends",
|
||||
function()
|
||||
local widgetCls = UnLuaExplicitWidget
|
||||
AssertEqual(widgetCls.Super, UnLuaBaseActor)
|
||||
local widget = CreateBoundInstance(widgetCls, "UUserWidget")
|
||||
widget:Construct({title = "MainHUD"})
|
||||
AssertEqual(
|
||||
widget:GetTitle(),
|
||||
"MainHUD"
|
||||
)
|
||||
end
|
||||
)
|
||||
end
|
||||
)
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,17 @@
|
||||
local Ex01_HelloWorld = UnLua.Class()
|
||||
function Ex01_HelloWorld.ReceiveBeginPlay(self)
|
||||
self.greeting = ("Hello UnLua from TypeScript (" .. _VERSION) .. ")!"
|
||||
UnLua.Log(self.greeting)
|
||||
UE.UKismetSystemLibrary.PrintString(
|
||||
self,
|
||||
self.greeting,
|
||||
true,
|
||||
true,
|
||||
UE.FLinearColor(0.1, 0.9, 0.4, 1),
|
||||
5
|
||||
)
|
||||
end
|
||||
function Ex01_HelloWorld.GetGreeting(self)
|
||||
return self.greeting
|
||||
end
|
||||
return Ex01_HelloWorld
|
||||
@@ -0,0 +1,54 @@
|
||||
local Ex02_OverrideBlueprintEvents = UnLua.Class()
|
||||
function Ex02_OverrideBlueprintEvents.Initialize(self, _Initializer)
|
||||
self.events = {"Initialize"}
|
||||
self.totalDamage = 0
|
||||
self.elapsed = 0
|
||||
self.overlapCount = 0
|
||||
end
|
||||
function Ex02_OverrideBlueprintEvents.UserConstructionScript(self)
|
||||
self.Overridden.UserConstructionScript(self)
|
||||
self.events[#self.events + 1] = "UserConstructionScript"
|
||||
end
|
||||
function Ex02_OverrideBlueprintEvents.ReceiveBeginPlay(self)
|
||||
self.Overridden.ReceiveBeginPlay(self)
|
||||
self.events[#self.events + 1] = "ReceiveBeginPlay"
|
||||
end
|
||||
function Ex02_OverrideBlueprintEvents.ReceiveTick(self, DeltaSeconds)
|
||||
self.Overridden.ReceiveTick(self, DeltaSeconds)
|
||||
self.elapsed = self.elapsed + DeltaSeconds
|
||||
end
|
||||
function Ex02_OverrideBlueprintEvents.ReceiveAnyDamage(self, Damage, _DamageType, _InstigatedBy, _DamageCauser)
|
||||
self.Overridden.ReceiveAnyDamage(
|
||||
self,
|
||||
Damage,
|
||||
_DamageType,
|
||||
_InstigatedBy,
|
||||
_DamageCauser
|
||||
)
|
||||
self.totalDamage = self.totalDamage + Damage
|
||||
self.events[#self.events + 1] = "Damage:" .. tostring(Damage)
|
||||
end
|
||||
function Ex02_OverrideBlueprintEvents.ReceiveActorBeginOverlap(self, OtherActor)
|
||||
self.Overridden.ReceiveActorBeginOverlap(self, OtherActor)
|
||||
if UE.UKismetSystemLibrary.IsValid(OtherActor) then
|
||||
self.overlapCount = self.overlapCount + 1
|
||||
self.events[#self.events + 1] = "Overlap:" .. OtherActor:GetName()
|
||||
end
|
||||
end
|
||||
function Ex02_OverrideBlueprintEvents.ReceiveEndPlay(self, EndPlayReason)
|
||||
self.Overridden.ReceiveEndPlay(self, EndPlayReason)
|
||||
self.events[#self.events + 1] = "EndPlay:" .. tostring(EndPlayReason)
|
||||
end
|
||||
function Ex02_OverrideBlueprintEvents.GetEvents(self)
|
||||
return self.events
|
||||
end
|
||||
function Ex02_OverrideBlueprintEvents.GetTotalDamage(self)
|
||||
return self.totalDamage
|
||||
end
|
||||
function Ex02_OverrideBlueprintEvents.GetElapsed(self)
|
||||
return self.elapsed
|
||||
end
|
||||
function Ex02_OverrideBlueprintEvents.GetOverlapCount(self)
|
||||
return self.overlapCount
|
||||
end
|
||||
return Ex02_OverrideBlueprintEvents
|
||||
@@ -0,0 +1,43 @@
|
||||
local Ex03_BindDelegates = UnLua.Class()
|
||||
function Ex03_BindDelegates.Construct(self)
|
||||
self.clickCount = 0
|
||||
self.timerTickCount = 0
|
||||
if self.ClickMeButton ~= nil then
|
||||
self.ClickMeButton.OnClicked:Add(self, self.OnButtonClicked)
|
||||
end
|
||||
if self.CustomSingleDelegate ~= nil then
|
||||
self.CustomSingleDelegate:Bind(self, self.OnCustomExecute)
|
||||
end
|
||||
self.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate({self, self.OnTimerTick}, 0.5, true)
|
||||
end
|
||||
function Ex03_BindDelegates.OnButtonClicked(self)
|
||||
self.clickCount = self.clickCount + 1
|
||||
end
|
||||
function Ex03_BindDelegates.OnCustomExecute(self, value)
|
||||
return value * 10 + self.clickCount
|
||||
end
|
||||
function Ex03_BindDelegates.OnTimerTick(self)
|
||||
if not UE.UKismetSystemLibrary.IsValid(self) then
|
||||
return
|
||||
end
|
||||
self.timerTickCount = self.timerTickCount + 1
|
||||
end
|
||||
function Ex03_BindDelegates.Destruct(self)
|
||||
if self.ClickMeButton ~= nil then
|
||||
self.ClickMeButton.OnClicked:Remove(self, self.OnButtonClicked)
|
||||
end
|
||||
if self.CustomSingleDelegate ~= nil then
|
||||
self.CustomSingleDelegate:Unbind()
|
||||
end
|
||||
UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(self, self.timerHandle)
|
||||
end
|
||||
function Ex03_BindDelegates.GetClickCount(self)
|
||||
return self.clickCount
|
||||
end
|
||||
function Ex03_BindDelegates.GetTimerTickCount(self)
|
||||
return self.timerTickCount
|
||||
end
|
||||
function Ex03_BindDelegates.GetTimerHandle(self)
|
||||
return self.timerHandle
|
||||
end
|
||||
return Ex03_BindDelegates
|
||||
@@ -0,0 +1,59 @@
|
||||
local Ex04_DynamicBinding = UnLua.Class()
|
||||
function Ex04_DynamicBinding.SpawnDynamicActor(self, tag, power)
|
||||
local world = self:GetWorld()
|
||||
local actorClass = UE.UClass.Load("/Game/Blueprints/BP_DynamicDemo.BP_DynamicDemo_C")
|
||||
if not world or not actorClass then
|
||||
return nil
|
||||
end
|
||||
local transform = UE.FTransform(
|
||||
UE.FRotator(0, 90, 0):ToQuat(),
|
||||
UE.FVector(100, 200, 300),
|
||||
UE.FVector(1, 1, 1)
|
||||
)
|
||||
return world:SpawnActor(
|
||||
actorClass,
|
||||
transform,
|
||||
UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn,
|
||||
self,
|
||||
nil,
|
||||
"Tests.UnLuaExamples.Ex04_DynamicSpawnedActor",
|
||||
{InitTag = tag, InitPower = power}
|
||||
)
|
||||
end
|
||||
function Ex04_DynamicBinding.SpawnDynamicActorEx(self, tag)
|
||||
local world = self:GetWorld()
|
||||
local actorClass = UE.LoadClass("/Game/Blueprints/BP_DynamicDemoEx.BP_DynamicDemoEx_C")
|
||||
if not world or not actorClass then
|
||||
return nil
|
||||
end
|
||||
local params = UE.FActorSpawnParameters()
|
||||
params.Name = "ExSpawnedActor"
|
||||
params.bNoFail = true
|
||||
params.Owner = self
|
||||
params.SpawnCollisionHandlingOverride = UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn
|
||||
return world:SpawnActorEx(
|
||||
actorClass,
|
||||
UE.FTransform(
|
||||
UE.FRotator(0, 0, 0):ToQuat(),
|
||||
UE.FVector(10, 20, 30),
|
||||
UE.FVector(1, 1, 1)
|
||||
),
|
||||
{InitTag = tag, InitPower = 77},
|
||||
"Tests.UnLuaExamples.Ex04_DynamicSpawnedActor",
|
||||
params
|
||||
)
|
||||
end
|
||||
function Ex04_DynamicBinding.CreateDynamicObject(self, seed)
|
||||
local objClass = UE.UClass.Load("/Script/CoreUObject.Object")
|
||||
if not objClass then
|
||||
return nil
|
||||
end
|
||||
return UE.NewObject(
|
||||
objClass,
|
||||
self,
|
||||
"DynamicObjectInstance",
|
||||
"Tests.UnLuaExamples.Ex04_DynamicObject",
|
||||
{Seed = seed}
|
||||
)
|
||||
end
|
||||
return Ex04_DynamicBinding
|
||||
@@ -0,0 +1,12 @@
|
||||
local Ex04_DynamicObject = UnLua.Class()
|
||||
function Ex04_DynamicObject.Initialize(self, Initializer)
|
||||
self.seed = Initializer and Initializer.Seed or 1
|
||||
end
|
||||
function Ex04_DynamicObject.NextValue(self)
|
||||
self.seed = self.seed * 2 + 1
|
||||
return self.seed
|
||||
end
|
||||
function Ex04_DynamicObject.GetSeed(self)
|
||||
return self.seed
|
||||
end
|
||||
return Ex04_DynamicObject
|
||||
@@ -0,0 +1,20 @@
|
||||
local Ex04_DynamicSpawnedActor = UnLua.Class()
|
||||
function Ex04_DynamicSpawnedActor.Initialize(self, Initializer)
|
||||
self.initTag = Initializer and Initializer.InitTag or "Default"
|
||||
self.initPower = Initializer and Initializer.InitPower or 0
|
||||
self.beginPlayCalled = false
|
||||
end
|
||||
function Ex04_DynamicSpawnedActor.ReceiveBeginPlay(self)
|
||||
self.Overridden.ReceiveBeginPlay(self)
|
||||
self.beginPlayCalled = true
|
||||
end
|
||||
function Ex04_DynamicSpawnedActor.GetInitTag(self)
|
||||
return self.initTag
|
||||
end
|
||||
function Ex04_DynamicSpawnedActor.GetInitPower(self)
|
||||
return self.initPower
|
||||
end
|
||||
function Ex04_DynamicSpawnedActor.IsBeginPlayCalled(self)
|
||||
return self.beginPlayCalled
|
||||
end
|
||||
return Ex04_DynamicSpawnedActor
|
||||
@@ -0,0 +1,73 @@
|
||||
local Ex05_BindInputs = UnLua.Class()
|
||||
function Ex05_BindInputs.ReceiveBeginPlay(self)
|
||||
self.Overridden.ReceiveBeginPlay(self)
|
||||
self.lastAction = ""
|
||||
self.moveForwardValue = 0
|
||||
self.enhancedCount = 0
|
||||
end
|
||||
function Ex05_BindInputs.HandleSpacePressed(self)
|
||||
self.lastAction = "SpaceBar:Pressed"
|
||||
end
|
||||
function Ex05_BindInputs.HandleCtrlSave(self)
|
||||
self.lastAction = "Ctrl+S"
|
||||
end
|
||||
function Ex05_BindInputs.HandleJumpAction(self)
|
||||
self.lastAction = "Action:Jump"
|
||||
end
|
||||
function Ex05_BindInputs.HandleMoveForward(self, axisValue)
|
||||
self.moveForwardValue = axisValue
|
||||
end
|
||||
function Ex05_BindInputs.HandleEnhancedMove(self, actionValue)
|
||||
self.enhancedCount = self.enhancedCount + 1
|
||||
self.moveForwardValue = actionValue
|
||||
end
|
||||
function Ex05_BindInputs.GetLastAction(self)
|
||||
return self.lastAction
|
||||
end
|
||||
function Ex05_BindInputs.GetMoveForwardValue(self)
|
||||
return self.moveForwardValue
|
||||
end
|
||||
function Ex05_BindInputs.GetEnhancedCount(self)
|
||||
return self.enhancedCount
|
||||
end
|
||||
UnLua.Input.BindKey(
|
||||
Ex05_BindInputs,
|
||||
"SpaceBar",
|
||||
"Pressed",
|
||||
function(self)
|
||||
self:HandleSpacePressed()
|
||||
end
|
||||
)
|
||||
UnLua.Input.BindKey(
|
||||
Ex05_BindInputs,
|
||||
"S",
|
||||
"Pressed",
|
||||
function(self)
|
||||
self:HandleCtrlSave()
|
||||
end,
|
||||
{Ctrl = true}
|
||||
)
|
||||
UnLua.Input.BindAction(
|
||||
Ex05_BindInputs,
|
||||
"Jump",
|
||||
"Pressed",
|
||||
function(self)
|
||||
self:HandleJumpAction()
|
||||
end
|
||||
)
|
||||
UnLua.Input.BindAxis(
|
||||
Ex05_BindInputs,
|
||||
"MoveForward",
|
||||
function(self, axisValue)
|
||||
self:HandleMoveForward(axisValue)
|
||||
end
|
||||
)
|
||||
UnLua.EnhancedInput.BindAction(
|
||||
Ex05_BindInputs,
|
||||
"/Game/Input/IA_Move.IA_Move",
|
||||
"Triggered",
|
||||
function(self, actionValue)
|
||||
self:HandleEnhancedMove(actionValue)
|
||||
end
|
||||
)
|
||||
return Ex05_BindInputs
|
||||
@@ -0,0 +1,201 @@
|
||||
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
|
||||
--- 参考 UnLua 官方示例 06_NativeContainers:
|
||||
-- 演示 UE.TArray / UE.TMap / UE.TSet 的构造(使用 UE.int32 / UE.FString Token)、
|
||||
-- 1-based 索引访问、CRUD、ToTable 与原生 pairs() 遍历。
|
||||
function ____exports.VerifyTArrayOperations()
|
||||
local arr = UE.TArray(UE.int32)
|
||||
AssertTrue(arr:Reserve(8))
|
||||
AssertEqual(
|
||||
arr:Length(),
|
||||
0
|
||||
)
|
||||
AssertEqual(
|
||||
arr:Add(10),
|
||||
1
|
||||
)
|
||||
AssertEqual(
|
||||
arr:Add(20),
|
||||
2
|
||||
)
|
||||
AssertEqual(
|
||||
arr:Add(30),
|
||||
3
|
||||
)
|
||||
AssertEqual(
|
||||
arr:Length(),
|
||||
3
|
||||
)
|
||||
AssertEqual(
|
||||
arr:Num(),
|
||||
3
|
||||
)
|
||||
AssertEqual(
|
||||
arr:Get(1),
|
||||
10
|
||||
)
|
||||
AssertEqual(
|
||||
arr:Get(3),
|
||||
30
|
||||
)
|
||||
AssertEqual(
|
||||
arr:LastIndex(),
|
||||
3
|
||||
)
|
||||
AssertTrue(arr:IsValidIndex(1))
|
||||
AssertFalse(arr:IsValidIndex(0))
|
||||
AssertFalse(arr:IsValidIndex(4))
|
||||
arr:Set(2, 25)
|
||||
AssertEqual(
|
||||
arr:Get(2),
|
||||
25
|
||||
)
|
||||
AssertEqual(
|
||||
arr:Find(25),
|
||||
2
|
||||
)
|
||||
AssertTrue(arr:Contains(25))
|
||||
AssertFalse(arr:Contains(999))
|
||||
AssertEqual(
|
||||
arr:AddUnique(25),
|
||||
0
|
||||
)
|
||||
AssertEqual(
|
||||
arr:AddUnique(40),
|
||||
4
|
||||
)
|
||||
AssertEqual(
|
||||
arr:Length(),
|
||||
4
|
||||
)
|
||||
arr:Insert(15, 2)
|
||||
AssertEqual(
|
||||
arr:Get(2),
|
||||
15
|
||||
)
|
||||
arr:Swap(1, 5)
|
||||
AssertEqual(
|
||||
arr:Get(1),
|
||||
40
|
||||
)
|
||||
AssertEqual(
|
||||
arr:Get(5),
|
||||
10
|
||||
)
|
||||
arr:Add(15)
|
||||
local removedCount = arr:RemoveItem(15)
|
||||
AssertEqual(removedCount, 2)
|
||||
AssertFalse(arr:Contains(15))
|
||||
local other = UE.TArray(UE.int32)
|
||||
other:Add(100)
|
||||
other:Add(200)
|
||||
arr:Append(other)
|
||||
local tbl = arr:ToTable()
|
||||
AssertArrayEqual(tbl, {
|
||||
40,
|
||||
25,
|
||||
30,
|
||||
10,
|
||||
100,
|
||||
200
|
||||
})
|
||||
local sum = 0
|
||||
for idx, val in pairs(arr) do
|
||||
AssertTrue(idx >= 1)
|
||||
sum = sum + val
|
||||
end
|
||||
AssertEqual(sum, 405)
|
||||
arr:Clear()
|
||||
AssertEqual(
|
||||
arr:Length(),
|
||||
0
|
||||
)
|
||||
end
|
||||
function ____exports.VerifyTMapOperations()
|
||||
local map = UE.TMap(UE.FString, UE.int32)
|
||||
map:Add("HP", 100)
|
||||
map:Add("MP", 50)
|
||||
map:Add("ATK", 35)
|
||||
AssertEqual(
|
||||
map:Length(),
|
||||
3
|
||||
)
|
||||
AssertEqual(
|
||||
map:Find("HP"),
|
||||
100
|
||||
)
|
||||
AssertEqual(
|
||||
map:FindRef("MP"),
|
||||
50
|
||||
)
|
||||
AssertNil(map:Find("DEF"))
|
||||
map:Add("HP", 120)
|
||||
AssertEqual(
|
||||
map:Find("HP"),
|
||||
120
|
||||
)
|
||||
AssertEqual(
|
||||
map:Keys():Length(),
|
||||
3
|
||||
)
|
||||
AssertEqual(
|
||||
map:Values():Length(),
|
||||
3
|
||||
)
|
||||
local tbl = map:ToTable()
|
||||
AssertEqual(tbl.ATK, 35)
|
||||
local sum = 0
|
||||
for _k, v in pairs(map) do
|
||||
sum = sum + v
|
||||
end
|
||||
AssertEqual(sum, 205)
|
||||
AssertTrue(map:Remove("MP"))
|
||||
AssertFalse(map:Remove("NotExist"))
|
||||
AssertEqual(
|
||||
map:Length(),
|
||||
2
|
||||
)
|
||||
map:Clear()
|
||||
AssertEqual(
|
||||
map:Length(),
|
||||
0
|
||||
)
|
||||
end
|
||||
function ____exports.VerifyTSetOperations()
|
||||
local set = UE.TSet(UE.FString)
|
||||
set:Add("Fire")
|
||||
set:Add("Ice")
|
||||
set:Add("Fire")
|
||||
AssertEqual(
|
||||
set:Length(),
|
||||
2
|
||||
)
|
||||
AssertTrue(set:Contains("Fire"))
|
||||
AssertFalse(set:Contains("Poison"))
|
||||
local asArr = set:ToArray()
|
||||
AssertEqual(
|
||||
asArr:Length(),
|
||||
2
|
||||
)
|
||||
AssertEqual(
|
||||
#set:ToTable(),
|
||||
2
|
||||
)
|
||||
AssertTrue(set:Remove("Ice"))
|
||||
AssertFalse(set:Remove("Ice"))
|
||||
AssertEqual(
|
||||
set:Length(),
|
||||
1
|
||||
)
|
||||
set:Clear()
|
||||
AssertEqual(
|
||||
set:Length(),
|
||||
0
|
||||
)
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,37 @@
|
||||
local Ex07_CallLatentFunction = UnLua.Class()
|
||||
function Ex07_CallLatentFunction.ReceiveBeginPlay(self)
|
||||
self.Overridden.ReceiveBeginPlay(self)
|
||||
self.steps = {}
|
||||
self.completed = false
|
||||
local co = coroutine.create(function(actor)
|
||||
actor:RunSequence()
|
||||
end)
|
||||
local ok, err = coroutine.resume(co, self)
|
||||
if not ok then
|
||||
UnLua.LogError(
|
||||
"Ex07 coroutine failed:",
|
||||
tostring(err)
|
||||
)
|
||||
end
|
||||
end
|
||||
function Ex07_CallLatentFunction.RunSequence(self)
|
||||
self.steps[#self.steps + 1] = "Step1:Start"
|
||||
UE.UKismetSystemLibrary.Delay(self, 0.5)
|
||||
if not UE.UKismetSystemLibrary.IsValid(self) then
|
||||
return
|
||||
end
|
||||
self.steps[#self.steps + 1] = "Step2:After0.5s"
|
||||
UE.UKismetSystemLibrary.Delay(self, 1)
|
||||
if not UE.UKismetSystemLibrary.IsValid(self) then
|
||||
return
|
||||
end
|
||||
self.steps[#self.steps + 1] = "Step3:Done"
|
||||
self.completed = true
|
||||
end
|
||||
function Ex07_CallLatentFunction.GetSteps(self)
|
||||
return self.steps
|
||||
end
|
||||
function Ex07_CallLatentFunction.IsCompleted(self)
|
||||
return self.completed
|
||||
end
|
||||
return Ex07_CallLatentFunction
|
||||
@@ -0,0 +1,43 @@
|
||||
local Ex08_StructAndTrace = UnLua.Class()
|
||||
function Ex08_StructAndTrace.ReceiveBeginPlay(self)
|
||||
self.Overridden.ReceiveBeginPlay(self)
|
||||
self._tmpStart = UE.FVector(0, 0, 0)
|
||||
self._tmpEnd = UE.FVector(0, 0, 0)
|
||||
self._tmpHit = UE.FHitResult()
|
||||
self._ignoreActors = UE.TArray(UE.AActor.StaticClass())
|
||||
self._ignoreActors:Add(self)
|
||||
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)
|
||||
local dist = UE.FVector.Dist(
|
||||
UE.FVector(0, 0, 0),
|
||||
c
|
||||
)
|
||||
return c: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(
|
||||
self,
|
||||
self._tmpStart,
|
||||
self._tmpEnd,
|
||||
UE.ETraceTypeQuery.TraceTypeQuery1,
|
||||
false,
|
||||
self._ignoreActors,
|
||||
UE.EDrawDebugTrace.None,
|
||||
self._tmpHit,
|
||||
true
|
||||
)
|
||||
return bHit, hit.Distance, hit.ImpactPoint
|
||||
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)
|
||||
return bMoved
|
||||
end
|
||||
return Ex08_StructAndTrace
|
||||
@@ -0,0 +1,44 @@
|
||||
local Ex09_AssetRefAndUMG = UnLua.Class()
|
||||
function Ex09_AssetRefAndUMG.Initialize(self, _Initializer)
|
||||
self.isConstructed = false
|
||||
self.isDestructed = false
|
||||
self.weakRef = UE.FWeakObjectPtr()
|
||||
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)
|
||||
end
|
||||
end
|
||||
function Ex09_AssetRefAndUMG.ShowOnScreen(self)
|
||||
self:AddToViewport(10)
|
||||
end
|
||||
function Ex09_AssetRefAndUMG.CloseAndRelease(self)
|
||||
self:RemoveFromParent()
|
||||
self:Destruct()
|
||||
self:Release()
|
||||
end
|
||||
function Ex09_AssetRefAndUMG.Destruct(self)
|
||||
if self.isDestructed then
|
||||
return
|
||||
end
|
||||
self.isDestructed = true
|
||||
if self.loadedAsset ~= nil then
|
||||
UnLua.Unref(self.loadedAsset)
|
||||
self.refProxy = nil
|
||||
self.loadedAsset = nil
|
||||
end
|
||||
self.weakRef:Reset()
|
||||
end
|
||||
function Ex09_AssetRefAndUMG.HasValidWeakAsset(self)
|
||||
return self.weakRef:IsValid()
|
||||
end
|
||||
function Ex09_AssetRefAndUMG.IsConstructed(self)
|
||||
return self.isConstructed
|
||||
end
|
||||
function Ex09_AssetRefAndUMG.IsDestructed(self)
|
||||
return self.isDestructed
|
||||
end
|
||||
return Ex09_AssetRefAndUMG
|
||||
@@ -0,0 +1,315 @@
|
||||
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 Ex01_HelloWorld = require("Tests.UnLuaExamples.Ex01_HelloWorld")
|
||||
local Ex02_OverrideBlueprintEvents = require("Tests.UnLuaExamples.Ex02_OverrideBlueprintEvents")
|
||||
local Ex03_BindDelegates = require("Tests.UnLuaExamples.Ex03_BindDelegates")
|
||||
local Ex04_DynamicBinding = require("Tests.UnLuaExamples.Ex04_DynamicBinding")
|
||||
local Ex05_BindInputs = require("Tests.UnLuaExamples.Ex05_BindInputs")
|
||||
local Ex07_CallLatentFunction = require("Tests.UnLuaExamples.Ex07_CallLatentFunction")
|
||||
local Ex08_StructAndTrace = require("Tests.UnLuaExamples.Ex08_StructAndTrace")
|
||||
local Ex09_AssetRefAndUMG = require("Tests.UnLuaExamples.Ex09_AssetRefAndUMG")
|
||||
function ____exports.RunUnLuaExamplesTests()
|
||||
Suite(
|
||||
"UnLuaExamples.OfficialPorts",
|
||||
function()
|
||||
Test(
|
||||
"Ex01_HelloWorld: ReceiveBeginPlay prints and logs greeting",
|
||||
function()
|
||||
ResetMockState()
|
||||
local actor = CreateBoundInstance(Ex01_HelloWorld, "AActor")
|
||||
actor:ReceiveBeginPlay()
|
||||
AssertTrue((string.find(
|
||||
actor:GetGreeting(),
|
||||
"Hello UnLua from TypeScript",
|
||||
1,
|
||||
true
|
||||
)) ~= nil)
|
||||
AssertEqual(
|
||||
#GetMockState().printedStrings,
|
||||
1
|
||||
)
|
||||
AssertEqual(
|
||||
#GetMockState().logs,
|
||||
1
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Ex02_OverrideBlueprintEvents: lifecycle events and self.Overridden chain",
|
||||
function()
|
||||
ResetMockState()
|
||||
local actor = CreateBoundInstance(Ex02_OverrideBlueprintEvents, "AActor")
|
||||
local other = CreateBoundInstance({}, "AActor", {__name = "OtherActor_1"})
|
||||
actor:Initialize()
|
||||
actor:UserConstructionScript()
|
||||
actor:ReceiveBeginPlay()
|
||||
actor:ReceiveTick(0.016)
|
||||
actor:ReceiveTick(0.034)
|
||||
actor:ReceiveAnyDamage(35, nil, nil, other)
|
||||
actor:ReceiveActorBeginOverlap(other)
|
||||
actor:ReceiveEndPlay(UE.EEndPlayReason.Destroyed)
|
||||
AssertNear(
|
||||
actor:GetElapsed(),
|
||||
0.05
|
||||
)
|
||||
AssertEqual(
|
||||
actor:GetTotalDamage(),
|
||||
35
|
||||
)
|
||||
AssertEqual(
|
||||
actor:GetOverlapCount(),
|
||||
1
|
||||
)
|
||||
AssertArrayEqual(
|
||||
actor:GetEvents(),
|
||||
{
|
||||
"Initialize",
|
||||
"UserConstructionScript",
|
||||
"ReceiveBeginPlay",
|
||||
"Damage:35",
|
||||
"Overlap:OtherActor_1",
|
||||
"EndPlay:0"
|
||||
}
|
||||
)
|
||||
AssertEqual(
|
||||
#GetMockState().overriddenCalls,
|
||||
7
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Ex03_BindDelegates: Multicast, FScriptDelegate and K2_SetTimerDelegate via UnLua.Delegate",
|
||||
function()
|
||||
ResetMockState()
|
||||
local mockBtn = {OnClicked = CreateMockMulticastDelegate()}
|
||||
local singleDel = CreateMockScriptDelegate()
|
||||
local widget = CreateBoundInstance(Ex03_BindDelegates, "UUserWidget", {ClickMeButton = mockBtn, CustomSingleDelegate = singleDel})
|
||||
widget:Construct()
|
||||
AssertTrue(mockBtn.OnClicked:IsBound())
|
||||
mockBtn.OnClicked:Broadcast()
|
||||
mockBtn.OnClicked:Broadcast()
|
||||
AssertEqual(
|
||||
widget:GetClickCount(),
|
||||
2
|
||||
)
|
||||
AssertEqual(
|
||||
singleDel:Execute(5),
|
||||
52
|
||||
)
|
||||
AdvanceMockTime(1.6)
|
||||
AssertEqual(
|
||||
widget:GetTimerTickCount(),
|
||||
3
|
||||
)
|
||||
AssertTrue(UE.UKismetSystemLibrary.K2_IsTimerActiveHandle(
|
||||
widget,
|
||||
widget:GetTimerHandle()
|
||||
))
|
||||
widget:Destruct()
|
||||
AssertFalse(mockBtn.OnClicked:IsBound())
|
||||
mockBtn.OnClicked:Broadcast()
|
||||
AssertEqual(
|
||||
widget:GetClickCount(),
|
||||
2
|
||||
)
|
||||
AdvanceMockTime(2)
|
||||
AssertEqual(
|
||||
widget:GetTimerTickCount(),
|
||||
3
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Ex04_DynamicBinding: World:SpawnActor, SpawnActorEx and UE.NewObject with Initializer",
|
||||
function()
|
||||
ResetMockState()
|
||||
local spawner = CreateBoundInstance(Ex04_DynamicBinding, "AActor")
|
||||
local spawned = spawner:SpawnDynamicActor("Fireball", 120)
|
||||
AssertNotNil(spawned)
|
||||
AssertEqual(
|
||||
spawned:GetInitTag(),
|
||||
"Fireball"
|
||||
)
|
||||
AssertEqual(
|
||||
spawned:GetInitPower(),
|
||||
120
|
||||
)
|
||||
AssertTrue(spawned:IsBeginPlayCalled())
|
||||
local spawnedEx = spawner:SpawnDynamicActorEx("IceShard")
|
||||
AssertNotNil(spawnedEx)
|
||||
AssertEqual(
|
||||
spawnedEx:GetInitTag(),
|
||||
"IceShard"
|
||||
)
|
||||
AssertEqual(
|
||||
spawnedEx:GetInitPower(),
|
||||
77
|
||||
)
|
||||
local dynObj = spawner:CreateDynamicObject(10)
|
||||
AssertNotNil(dynObj)
|
||||
AssertEqual(
|
||||
dynObj:GetSeed(),
|
||||
10
|
||||
)
|
||||
AssertEqual(
|
||||
dynObj:NextValue(),
|
||||
21
|
||||
)
|
||||
AssertEqual(
|
||||
dynObj:NextValue(),
|
||||
43
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Ex05_BindInputs: UnLua.Input and UnLua.EnhancedInput module registrations",
|
||||
function()
|
||||
local pc = CreateBoundInstance(Ex05_BindInputs, "APlayerController")
|
||||
pc:ReceiveBeginPlay()
|
||||
ResetMockState()
|
||||
local pkg = _G.package
|
||||
local modName = "Tests.UnLuaExamples.Ex05_BindInputs"
|
||||
local prevMod = pkg.loaded[modName]
|
||||
pkg.loaded[modName] = nil
|
||||
require(modName)
|
||||
pkg.loaded[modName] = prevMod
|
||||
local bindings = GetMockState().inputBindings
|
||||
AssertEqual(#bindings, 5)
|
||||
AssertEqual(bindings[1].kind, "Key")
|
||||
AssertEqual(bindings[1].name, "SpaceBar")
|
||||
local ____AssertEqual_2 = AssertEqual
|
||||
local ____opt_0 = bindings[2].args
|
||||
____AssertEqual_2(____opt_0 and ____opt_0.Ctrl, true)
|
||||
AssertEqual(bindings[3].kind, "Action")
|
||||
AssertEqual(bindings[4].kind, "Axis")
|
||||
AssertEqual(bindings[5].kind, "EnhancedAction")
|
||||
bindings[1].handler(pc)
|
||||
AssertEqual(
|
||||
pc:GetLastAction(),
|
||||
"SpaceBar:Pressed"
|
||||
)
|
||||
bindings[2].handler(pc)
|
||||
AssertEqual(
|
||||
pc:GetLastAction(),
|
||||
"Ctrl+S"
|
||||
)
|
||||
bindings[3].handler(pc)
|
||||
AssertEqual(
|
||||
pc:GetLastAction(),
|
||||
"Action:Jump"
|
||||
)
|
||||
bindings[4].handler(pc, 0.75)
|
||||
AssertNear(
|
||||
pc:GetMoveForwardValue(),
|
||||
0.75
|
||||
)
|
||||
bindings[5].handler(pc, -1)
|
||||
AssertNear(
|
||||
pc:GetMoveForwardValue(),
|
||||
-1
|
||||
)
|
||||
AssertEqual(
|
||||
pc:GetEnhancedCount(),
|
||||
1
|
||||
)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Ex06_NativeContainers: TArray, TMap and TSet full API & pairs()",
|
||||
function()
|
||||
VerifyTArrayOperations()
|
||||
VerifyTMapOperations()
|
||||
VerifyTSetOperations()
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Ex07_CallLatentFunction: coroutine Delay sequence & destroy abort guard",
|
||||
function()
|
||||
ResetMockState()
|
||||
local actor = CreateBoundInstance(Ex07_CallLatentFunction, "AActor")
|
||||
actor:ReceiveBeginPlay()
|
||||
AssertArrayEqual(
|
||||
actor:GetSteps(),
|
||||
{"Step1:Start"}
|
||||
)
|
||||
AssertFalse(actor:IsCompleted())
|
||||
AdvanceMockTime(0.5)
|
||||
AssertArrayEqual(
|
||||
actor:GetSteps(),
|
||||
{"Step1:Start", "Step2:After0.5s"}
|
||||
)
|
||||
AssertFalse(actor:IsCompleted())
|
||||
AdvanceMockTime(1)
|
||||
AssertArrayEqual(
|
||||
actor:GetSteps(),
|
||||
{"Step1:Start", "Step2:After0.5s", "Step3:Done"}
|
||||
)
|
||||
AssertTrue(actor:IsCompleted())
|
||||
local doomed = CreateBoundInstance(Ex07_CallLatentFunction, "AActor")
|
||||
doomed:ReceiveBeginPlay()
|
||||
doomed:K2_DestroyActor()
|
||||
AdvanceMockTime(2)
|
||||
AssertArrayEqual(
|
||||
doomed:GetSteps(),
|
||||
{"Step1:Start"}
|
||||
)
|
||||
AssertFalse(doomed:IsCompleted())
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Ex08_StructAndTrace: FVector math, LineTraceSingle multi-return and K2_SetActorLocation",
|
||||
function()
|
||||
ResetMockState()
|
||||
local actor = CreateBoundInstance(Ex08_StructAndTrace, "AActor")
|
||||
actor:ReceiveBeginPlay()
|
||||
local size, dot, dist = actor:ComputeVectorMath()
|
||||
AssertNear(size, 13)
|
||||
AssertNear(dot, 0)
|
||||
AssertNear(dist, 13)
|
||||
AssertTrue(actor:TeleportTo(100, 0, 50))
|
||||
local bHit, hitDist, impact = actor:TraceForward(200)
|
||||
AssertTrue(bHit)
|
||||
AssertNear(hitDist, 100)
|
||||
AssertNear(impact.X, 200)
|
||||
AssertNear(impact.Z, 50)
|
||||
end
|
||||
)
|
||||
Test(
|
||||
"Ex09_AssetRefAndUMG: UObject.Load, UnLua.Ref/Unref, WeakPtr and UMG Release",
|
||||
function()
|
||||
ResetMockState()
|
||||
local widget = CreateBoundInstance(Ex09_AssetRefAndUMG, "UUserWidget")
|
||||
widget:Initialize()
|
||||
widget:Construct()
|
||||
widget:ShowOnScreen()
|
||||
AssertTrue(widget:IsConstructed())
|
||||
AssertFalse(widget:IsDestructed())
|
||||
AssertTrue(widget:HasValidWeakAsset())
|
||||
widget:CloseAndRelease()
|
||||
AssertTrue(widget:IsDestructed())
|
||||
AssertFalse(widget:HasValidWeakAsset())
|
||||
end
|
||||
)
|
||||
end
|
||||
)
|
||||
end
|
||||
return ____exports
|
||||
@@ -0,0 +1,223 @@
|
||||
local function __TS__CountVarargs(...)
|
||||
return select("#", ...)
|
||||
end
|
||||
|
||||
local function __TS__SparseArrayNew(...)
|
||||
local sparseArray = {...}
|
||||
sparseArray.sparseLength = __TS__CountVarargs(...)
|
||||
return sparseArray
|
||||
end
|
||||
|
||||
local function __TS__SparseArrayPush(sparseArray, ...)
|
||||
local args = {...}
|
||||
local argsLen = __TS__CountVarargs(...)
|
||||
local listLen = sparseArray.sparseLength
|
||||
for i = 1, argsLen do
|
||||
sparseArray[listLen + i] = args[i]
|
||||
end
|
||||
sparseArray.sparseLength = listLen + argsLen
|
||||
end
|
||||
|
||||
local function __TS__SparseArraySpread(sparseArray)
|
||||
local _unpack = unpack or table.unpack
|
||||
return _unpack(sparseArray, 1, sparseArray.sparseLength)
|
||||
end
|
||||
|
||||
local function __TS__ArraySplice(self, ...)
|
||||
local args = {...}
|
||||
local len = #self
|
||||
local actualArgumentCount = __TS__CountVarargs(...)
|
||||
local start = args[1]
|
||||
local deleteCount = args[2]
|
||||
if start < 0 then
|
||||
start = len + start
|
||||
if start < 0 then
|
||||
start = 0
|
||||
end
|
||||
elseif start > len then
|
||||
start = len
|
||||
end
|
||||
local itemCount = actualArgumentCount - 2
|
||||
if itemCount < 0 then
|
||||
itemCount = 0
|
||||
end
|
||||
local actualDeleteCount
|
||||
if actualArgumentCount == 0 then
|
||||
actualDeleteCount = 0
|
||||
elseif actualArgumentCount == 1 then
|
||||
actualDeleteCount = len - start
|
||||
else
|
||||
actualDeleteCount = deleteCount or 0
|
||||
if actualDeleteCount < 0 then
|
||||
actualDeleteCount = 0
|
||||
end
|
||||
if actualDeleteCount > len - start then
|
||||
actualDeleteCount = len - start
|
||||
end
|
||||
end
|
||||
local out = {}
|
||||
for k = 1, actualDeleteCount do
|
||||
local from = start + k
|
||||
if self[from] ~= nil then
|
||||
out[k] = self[from]
|
||||
end
|
||||
end
|
||||
if itemCount < actualDeleteCount then
|
||||
for k = start + 1, len - actualDeleteCount do
|
||||
local from = k + actualDeleteCount
|
||||
local to = k + itemCount
|
||||
if self[from] then
|
||||
self[to] = self[from]
|
||||
else
|
||||
self[to] = nil
|
||||
end
|
||||
end
|
||||
for k = len - actualDeleteCount + itemCount + 1, len do
|
||||
self[k] = nil
|
||||
end
|
||||
elseif itemCount > actualDeleteCount then
|
||||
for k = len - actualDeleteCount, start + 1, -1 do
|
||||
local from = k + actualDeleteCount
|
||||
local to = k + itemCount
|
||||
if self[from] then
|
||||
self[to] = self[from]
|
||||
else
|
||||
self[to] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
local j = start + 1
|
||||
for i = 3, actualArgumentCount do
|
||||
self[j] = args[i]
|
||||
j = j + 1
|
||||
end
|
||||
for k = #self, len - actualDeleteCount + itemCount + 1, -1 do
|
||||
self[k] = nil
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function __TS__ArraySort(self, compareFn)
|
||||
if compareFn ~= nil then
|
||||
table.sort(
|
||||
self,
|
||||
function(a, b) return compareFn(nil, a, b) < 0 end
|
||||
)
|
||||
else
|
||||
table.sort(self)
|
||||
end
|
||||
return self
|
||||
end
|
||||
|
||||
local function __TS__ArrayIndexOf(self, searchElement, fromIndex)
|
||||
if fromIndex == nil then
|
||||
fromIndex = 0
|
||||
end
|
||||
local len = #self
|
||||
if len == 0 then
|
||||
return -1
|
||||
end
|
||||
if fromIndex >= len then
|
||||
return -1
|
||||
end
|
||||
if fromIndex < 0 then
|
||||
fromIndex = len + fromIndex
|
||||
if fromIndex < 0 then
|
||||
fromIndex = 0
|
||||
end
|
||||
end
|
||||
for i = fromIndex + 1, len do
|
||||
if self[i] == searchElement then
|
||||
return i - 1
|
||||
end
|
||||
end
|
||||
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)
|
||||
setmetatable(target, staticMetatable)
|
||||
local baseMetatable = getmetatable(base)
|
||||
if baseMetatable then
|
||||
if type(baseMetatable.__index) == "function" then
|
||||
staticMetatable.__index = baseMetatable.__index
|
||||
end
|
||||
if type(baseMetatable.__newindex) == "function" then
|
||||
staticMetatable.__newindex = baseMetatable.__newindex
|
||||
end
|
||||
end
|
||||
setmetatable(target.prototype, base.prototype)
|
||||
if type(base.prototype.__index) == "function" then
|
||||
target.prototype.__index = base.prototype.__index
|
||||
end
|
||||
if type(base.prototype.__newindex) == "function" then
|
||||
target.prototype.__newindex = base.prototype.__newindex
|
||||
end
|
||||
if type(base.prototype.__tostring) == "function" then
|
||||
target.prototype.__tostring = base.prototype.__tostring
|
||||
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)
|
||||
return ("Symbol(" .. (self.description or "")) .. ")"
|
||||
end}
|
||||
function __TS__Symbol(description)
|
||||
return setmetatable({description = description}, symbolMetatable)
|
||||
end
|
||||
Symbol = {
|
||||
asyncDispose = __TS__Symbol("Symbol.asyncDispose"),
|
||||
dispose = __TS__Symbol("Symbol.dispose"),
|
||||
iterator = __TS__Symbol("Symbol.iterator"),
|
||||
hasInstance = __TS__Symbol("Symbol.hasInstance"),
|
||||
species = __TS__Symbol("Symbol.species"),
|
||||
toStringTag = __TS__Symbol("Symbol.toStringTag")
|
||||
}
|
||||
end
|
||||
|
||||
local function __TS__InstanceOf(obj, classTbl)
|
||||
if type(classTbl) ~= "table" then
|
||||
error("Right-hand side of 'instanceof' is not an object", 0)
|
||||
end
|
||||
if classTbl[Symbol.hasInstance] ~= nil then
|
||||
return not not classTbl[Symbol.hasInstance](classTbl, obj)
|
||||
end
|
||||
if type(obj) == "table" then
|
||||
local luaClass = obj.constructor
|
||||
while luaClass ~= nil do
|
||||
if luaClass == classTbl then
|
||||
return true
|
||||
end
|
||||
luaClass = luaClass.____super
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
return {
|
||||
__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
|
||||
}
|
||||
+16
-6
@@ -18,12 +18,19 @@ Script/ts/
|
||||
│ ├── EventBus.ts
|
||||
│ ├── HotReload.ts
|
||||
│ └── Log.ts
|
||||
└── Game/ # UnLua 绑定类(@unlua)
|
||||
├── LuaGameInstance.ts
|
||||
├── LuaGameMode.ts
|
||||
├── LuaPlayerController.ts
|
||||
├── LuaCharacter.ts
|
||||
└── LuaDemoActor.ts
|
||||
├── Game/ # UnLua 绑定类(@unlua)
|
||||
│ ├── LuaGameInstance.ts
|
||||
│ ├── LuaGameMode.ts
|
||||
│ ├── LuaPlayerController.ts
|
||||
│ ├── LuaCharacter.ts
|
||||
│ └── LuaDemoActor.ts
|
||||
└── Tests/ # TypeScript -> Lua 5.4 自动化测试套件
|
||||
├── Harness/ # 轻量级测试运行器与独立 Lua 5.4 UnLua/UE Mock 环境
|
||||
├── Syntax/ # ts2lua 语法、容器、泛型与 @unlua 继承/静态/解构特性测试
|
||||
├── UnLuaExamples/ # 参考 UnLua 官方示例 01~09 的 TS 移植与验证
|
||||
├── Gameplay/ # 常用游戏系统实现(FSM/对象池/定时器/Buff属性/背包/协程/行为树)
|
||||
├── Extra/ # 框架集成、热重载、Lua 5.4 陷阱与生命周期安全测试
|
||||
└── RunAllTests.ts # 统一测试入口(支持 lua5.4 独立运行或在 UE 内调用)
|
||||
```
|
||||
|
||||
## 常用命令
|
||||
@@ -37,6 +44,9 @@ npm install
|
||||
# 全量编译到 ../lua
|
||||
npm run build
|
||||
|
||||
# 编译并在本机 Lua 5.4 下运行全部自动化测试
|
||||
npm test
|
||||
|
||||
# 增量监听模式(开发期配合 PIE + UnLua HotReload 使用)
|
||||
npm run watch
|
||||
|
||||
|
||||
Generated
+3
-3
@@ -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.1"
|
||||
"ts2lua-unreal": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#v0.2.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-to-lua/language-extensions": {
|
||||
@@ -175,8 +175,8 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ts2lua-unreal": {
|
||||
"version": "0.2.1",
|
||||
"resolved": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#70630f689f8ae470654854d68cb3d88b99a60ef3",
|
||||
"version": "0.2.2",
|
||||
"resolved": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#cb1539d7383e72b32d0fae600199257a05f4d416",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"lua-types": "^2.14.1",
|
||||
|
||||
@@ -6,9 +6,10 @@
|
||||
"scripts": {
|
||||
"build": "ts2lua-unreal build",
|
||||
"watch": "ts2lua-unreal watch",
|
||||
"test": "npm run build && node scripts/run-tests.mjs",
|
||||
"info": "ts2lua-unreal info"
|
||||
},
|
||||
"devDependencies": {
|
||||
"ts2lua-unreal": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#v0.2.1"
|
||||
"ts2lua-unreal": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#v0.2.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env node
|
||||
import * as path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
const tsRoot = path.resolve(import.meta.dirname, "..");
|
||||
const luaRoot = path.resolve(tsRoot, "..", "lua");
|
||||
|
||||
const luaBin = ["lua5.4", "lua"].find((cmd) => {
|
||||
const probe = spawnSync(cmd, ["-v"], { encoding: "utf8" });
|
||||
return probe.status === 0 && /Lua 5\.4/.test((probe.stdout || "") + (probe.stderr || ""));
|
||||
});
|
||||
|
||||
if (!luaBin) {
|
||||
console.error("[run-tests] Lua 5.4 interpreter (lua5.4 / lua) not found in PATH.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const luaPath = [
|
||||
path.join(luaRoot, "?.lua"),
|
||||
path.join(luaRoot, "?", "init.lua"),
|
||||
process.env.LUA_PATH || "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(";");
|
||||
|
||||
const code = `
|
||||
package.path = ${JSON.stringify(luaPath)} .. ";" .. package.path
|
||||
require("Tests.Harness.MockUnLuaRuntime").InstallIfNeeded()
|
||||
_G.__TS2LUA_TEST_AUTO_RUN__ = true
|
||||
require("Tests.RunAllTests")
|
||||
`;
|
||||
|
||||
const result = spawnSync(luaBin, ["-e", code], {
|
||||
stdio: "inherit",
|
||||
cwd: luaRoot,
|
||||
});
|
||||
|
||||
process.exit(result.status ?? 1);
|
||||
@@ -0,0 +1,161 @@
|
||||
/** @noSelfInFile */
|
||||
|
||||
import {
|
||||
Suite,
|
||||
Test,
|
||||
AssertEqual,
|
||||
AssertTrue,
|
||||
AssertFalse,
|
||||
AssertNotNil,
|
||||
AssertNil,
|
||||
AssertArrayEqual,
|
||||
} from "../Harness/TestRunner";
|
||||
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";
|
||||
|
||||
export function RunHotReloadAndFrameworkTests(): void {
|
||||
Suite("Extra.FrameworkAndHotReload", () => {
|
||||
Test("EventBus: dedup, owner dispatch, mid-emit unsubscribe, OffAllForOwner and error isolation", () => {
|
||||
EventBus.Clear();
|
||||
const received: string[] = [];
|
||||
|
||||
interface OwnerObj {
|
||||
tag: string;
|
||||
OnEvent(this: OwnerObj, msg: string): void;
|
||||
}
|
||||
const ownerA: OwnerObj = {
|
||||
tag: "A",
|
||||
OnEvent(this: OwnerObj, msg: string) {
|
||||
received[received.length] = `${this.tag}:${msg}`;
|
||||
},
|
||||
};
|
||||
const ownerB: OwnerObj = {
|
||||
tag: "B",
|
||||
OnEvent(this: OwnerObj, msg: string) {
|
||||
received[received.length] = `${this.tag}:${msg}`;
|
||||
// 在回调执行期间取消自己
|
||||
EventBus.Off("Test.Ping", this.OnEvent, this);
|
||||
},
|
||||
};
|
||||
|
||||
// 重复注册应自动去重
|
||||
EventBus.On("Test.Ping", ownerA.OnEvent, ownerA);
|
||||
EventBus.On("Test.Ping", ownerA.OnEvent, ownerA);
|
||||
EventBus.On("Test.Ping", ownerB.OnEvent, ownerB);
|
||||
|
||||
// 注册一个会抛错的监听者,验证 EventBus 内 pcall 隔离不影响其他监听者
|
||||
EventBus.On("Test.Ping", () => {
|
||||
error("intentional listener error");
|
||||
});
|
||||
|
||||
let afterErrorCalled = false;
|
||||
EventBus.On("Test.Ping", () => {
|
||||
afterErrorCalled = true;
|
||||
});
|
||||
|
||||
EventBus.Emit("Test.Ping", "hello");
|
||||
AssertArrayEqual(received, ["A:hello", "B:hello"]);
|
||||
AssertTrue(afterErrorCalled);
|
||||
|
||||
// 第二次 Emit:ownerB 已自退订
|
||||
EventBus.Emit("Test.Ping", "world");
|
||||
AssertArrayEqual(received, ["A:hello", "B:hello", "A:world"]);
|
||||
|
||||
// OffAllForOwner 清理 ownerA
|
||||
EventBus.OffAllForOwner(ownerA);
|
||||
EventBus.Emit("Test.Ping", "ignored");
|
||||
AssertArrayEqual(received, ["A:hello", "B:hello", "A:world"]);
|
||||
|
||||
EventBus.Clear();
|
||||
});
|
||||
|
||||
Test("Bootstrap Init/Shutdown lifecycle and _G.GameFramework registration", () => {
|
||||
const fakeGI = CreateBoundInstance<UE.ULuaGameInstance>({}, "ULuaGameInstance");
|
||||
Bootstrap.Init(fakeGI);
|
||||
AssertTrue(Bootstrap.IsInitialized);
|
||||
AssertEqual(Bootstrap.GameInstance, fakeGI);
|
||||
AssertNotNil(_G.GameFramework);
|
||||
|
||||
Bootstrap.Shutdown();
|
||||
AssertFalse(Bootstrap.IsInitialized);
|
||||
AssertNil(Bootstrap.GameInstance);
|
||||
AssertNil(_G.GameFramework);
|
||||
});
|
||||
|
||||
Test("HotReload.ReloadModule validates arguments and emits Before/After events", () => {
|
||||
EventBus.Clear();
|
||||
const [badOk, badErr] = HotReload.ReloadModule("");
|
||||
AssertFalse(badOk);
|
||||
AssertEqual(badErr, "Invalid module name");
|
||||
|
||||
const order: string[] = [];
|
||||
EventBus.On(HotReload.EVENT_BEFORE_RELOAD, (modName: string) => {
|
||||
order[order.length] = "before:" + modName;
|
||||
});
|
||||
EventBus.On(HotReload.EVENT_AFTER_RELOAD, (modName: string) => {
|
||||
order[order.length] = "after:" + modName;
|
||||
});
|
||||
|
||||
const [ok] = HotReload.ReloadModule("Framework.Log");
|
||||
AssertTrue(ok);
|
||||
AssertArrayEqual(order, ["before:Framework.Log", "after:Framework.Log"]);
|
||||
EventBus.Clear();
|
||||
});
|
||||
|
||||
Test("LuaDemoActor full integration: BeginPlay, Tick, Ping color cycle, HotReload event & EndPlay cleanup", () => {
|
||||
ResetMockState();
|
||||
EventBus.Clear();
|
||||
|
||||
let lastStatusText = "";
|
||||
let colorApplyCount = 0;
|
||||
let rotationAddCount = 0;
|
||||
let lastVerticalOffset = 0;
|
||||
|
||||
const demoActor = CreateBoundInstance<LuaDemoActor>(
|
||||
LuaDemoActor as unknown as Record<string, any>,
|
||||
"ALuaDemoActor",
|
||||
{
|
||||
SpinSpeed: 90,
|
||||
BobAmplitude: 20,
|
||||
BobFrequency: 2,
|
||||
SetStatusText(this: unknown, text: string) {
|
||||
lastStatusText = text;
|
||||
},
|
||||
SetCubeColor(this: unknown, _color: UE.FLinearColor) {
|
||||
colorApplyCount++;
|
||||
},
|
||||
AddCubeLocalRotation(this: unknown, _delta: UE.FRotator) {
|
||||
rotationAddCount++;
|
||||
},
|
||||
SetCubeVerticalOffset(this: unknown, zOffset: number) {
|
||||
lastVerticalOffset = zOffset;
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
demoActor.ReceiveBeginPlay();
|
||||
AssertEqual(colorApplyCount, 1);
|
||||
AssertTrue(string.find(lastStatusText, "Pings: 0", 1, true)[0] !== undefined);
|
||||
|
||||
demoActor.ReceiveTick(0.25);
|
||||
AssertEqual(rotationAddCount, 1);
|
||||
AssertTrue(lastVerticalOffset !== 0);
|
||||
|
||||
EventBus.Emit("Demo.Ping", "TestSuite");
|
||||
AssertEqual(colorApplyCount, 2);
|
||||
AssertTrue(string.find(lastStatusText, "Pings: 1", 1, true)[0] !== undefined);
|
||||
|
||||
EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, "Game.LuaDemoActor");
|
||||
AssertTrue(string.find(lastStatusText, "Reloads: 1", 1, true)[0] !== undefined);
|
||||
|
||||
// EndPlay 后不再响应 EventBus
|
||||
demoActor.ReceiveEndPlay(UE.EEndPlayReason.Destroyed);
|
||||
EventBus.Emit("Demo.Ping", "AfterEndPlay");
|
||||
AssertEqual(colorApplyCount, 2);
|
||||
EventBus.Clear();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/** @noSelfInFile */
|
||||
|
||||
import {
|
||||
Suite,
|
||||
Test,
|
||||
AssertEqual,
|
||||
AssertTrue,
|
||||
AssertFalse,
|
||||
AssertNil,
|
||||
AssertArrayEqual,
|
||||
} from "../Harness/TestRunner";
|
||||
import {
|
||||
AdvanceMockTime,
|
||||
CreateBoundInstance,
|
||||
GetMockState,
|
||||
ResetMockState,
|
||||
} from "../Harness/MockUnLuaRuntime";
|
||||
import * as EventBus from "../../Framework/EventBus";
|
||||
import LifecycleSafetyActor from "./LifecycleSafetyActor";
|
||||
|
||||
export function RunLifecycleAndMemoryTests(): void {
|
||||
Suite("Extra.LifecycleAndMemorySafety", () => {
|
||||
Test("multiple @unlua instances maintain isolated state (no shared class-table arrays)", () => {
|
||||
ResetMockState();
|
||||
EventBus.Clear();
|
||||
|
||||
const cls = LifecycleSafetyActor as unknown as Record<string, any>;
|
||||
const a = CreateBoundInstance<LifecycleSafetyActor>(cls, "AActor");
|
||||
const b = CreateBoundInstance<LifecycleSafetyActor>(cls, "AActor");
|
||||
|
||||
a.ReceiveBeginPlay();
|
||||
b.ReceiveBeginPlay();
|
||||
|
||||
a.PushItem("only_in_a");
|
||||
b.PushItem("only_in_b");
|
||||
|
||||
AssertArrayEqual(a.GetItems(), ["only_in_a"]);
|
||||
AssertArrayEqual(b.GetItems(), ["only_in_b"]);
|
||||
|
||||
a.ReceiveEndPlay(UE.EEndPlayReason.Destroyed);
|
||||
b.ReceiveEndPlay(UE.EEndPlayReason.Destroyed);
|
||||
EventBus.Clear();
|
||||
});
|
||||
|
||||
Test("paired cleanup on ReceiveEndPlay prevents leaked EventBus, Delegate, Timer & manual Ref", () => {
|
||||
ResetMockState();
|
||||
EventBus.Clear();
|
||||
|
||||
const actor = CreateBoundInstance<LifecycleSafetyActor>(
|
||||
LifecycleSafetyActor as unknown as Record<string, any>,
|
||||
"AActor"
|
||||
);
|
||||
const asset = UE.UObject.Load("/Game/Data/DA_Config.DA_Config")!;
|
||||
const weak = UE.FWeakObjectPtr();
|
||||
weak.Set(actor);
|
||||
|
||||
actor.ReceiveBeginPlay();
|
||||
actor.HoldManualRef(asset);
|
||||
AssertEqual(GetMockState().manualRefs.get(asset as unknown as object), 1);
|
||||
|
||||
EventBus.Emit("Lifecycle.Broadcast", "msg1");
|
||||
actor.OnTakeAnyDamage.Broadcast(actor, 25, undefined, undefined, undefined);
|
||||
AdvanceMockTime(1.0);
|
||||
AssertEqual(actor.GetReceivedEvents(), 3);
|
||||
AssertTrue(weak.IsValid());
|
||||
|
||||
// 触发 EndPlay 与销毁
|
||||
actor.ReceiveEndPlay(UE.EEndPlayReason.Destroyed);
|
||||
actor.K2_DestroyActor();
|
||||
|
||||
AssertFalse(actor.OnTakeAnyDamage.IsBound());
|
||||
AssertFalse(weak.IsValid());
|
||||
AssertNil(weak.Get());
|
||||
AssertNil(GetMockState().manualRefs.get(asset as unknown as object));
|
||||
|
||||
// 销毁后再次广播事件/推进时间,计数不应再增长
|
||||
EventBus.Emit("Lifecycle.Broadcast", "msg2");
|
||||
AdvanceMockTime(3.0);
|
||||
AssertEqual(actor.GetReceivedEvents(), 3);
|
||||
EventBus.Clear();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import * as EventBus from "../../Framework/EventBus";
|
||||
|
||||
/**
|
||||
* 演示多实例隔离、配对清理(EventBus + Delegate + Timer + UnLua.Ref)与销毁后安全防护的 @unlua Actor。
|
||||
*/
|
||||
@unlua
|
||||
export default class LifecycleSafetyActor extends UE.AActor {
|
||||
private items!: string[];
|
||||
private receivedEvents!: number;
|
||||
private timerHandle!: UE.FTimerHandle;
|
||||
private keptRef!: UE.UObject | undefined;
|
||||
|
||||
ReceiveBeginPlay(): void {
|
||||
super.ReceiveBeginPlay();
|
||||
// 每个实例独立初始化,严禁类字段初始化导致多实例共享表
|
||||
this.items = [];
|
||||
this.receivedEvents = 0;
|
||||
|
||||
EventBus.On("Lifecycle.Broadcast", this.OnBroadcast, this);
|
||||
this.OnTakeAnyDamage.Add(this, this.OnDamaged);
|
||||
this.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate(
|
||||
UnLua.Delegate(this, this.OnHeartbeat),
|
||||
1.0,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
PushItem(item: string): void {
|
||||
this.items[this.items.length] = item;
|
||||
}
|
||||
|
||||
GetItems(): string[] {
|
||||
return this.items;
|
||||
}
|
||||
|
||||
HoldManualRef(asset: UE.UObject): void {
|
||||
this.keptRef = asset;
|
||||
UnLua.Ref(asset);
|
||||
}
|
||||
|
||||
OnBroadcast(tag: string): void {
|
||||
if (!UE.UKismetSystemLibrary.IsValid(this)) return;
|
||||
this.receivedEvents++;
|
||||
this.items[this.items.length] = tag;
|
||||
}
|
||||
|
||||
OnDamaged(
|
||||
_DamagedActor: UE.AActor | undefined,
|
||||
Damage: number,
|
||||
_DamageType: UE.UDamageType | undefined,
|
||||
_InstigatedBy: UE.AController | undefined,
|
||||
_DamageCauser: UE.AActor | undefined
|
||||
): void {
|
||||
if (!UE.UKismetSystemLibrary.IsValid(this)) return;
|
||||
this.receivedEvents++;
|
||||
this.items[this.items.length] = `dmg:${Damage}`;
|
||||
}
|
||||
|
||||
OnHeartbeat(): void {
|
||||
if (!UE.UKismetSystemLibrary.IsValid(this)) return;
|
||||
this.receivedEvents++;
|
||||
}
|
||||
|
||||
GetReceivedEvents(): number {
|
||||
return this.receivedEvents;
|
||||
}
|
||||
|
||||
ReceiveEndPlay(EndPlayReason: UE.EEndPlayReason): void {
|
||||
EventBus.OffAllForOwner(this);
|
||||
this.OnTakeAnyDamage.Remove(this, this.OnDamaged);
|
||||
UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(this, this.timerHandle);
|
||||
if (this.keptRef !== undefined) {
|
||||
UnLua.Unref(this.keptRef);
|
||||
this.keptRef = undefined;
|
||||
}
|
||||
super.ReceiveEndPlay(EndPlayReason);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/** @noSelfInFile */
|
||||
|
||||
import {
|
||||
Suite,
|
||||
Test,
|
||||
AssertEqual,
|
||||
AssertTrue,
|
||||
AssertFalse,
|
||||
AssertNear,
|
||||
AssertArrayEqual,
|
||||
} from "../Harness/TestRunner";
|
||||
|
||||
function EscapeLuaPattern(literal: string): string {
|
||||
const [escaped] = string.gsub(literal, "([%(%)%.%%%+%-%*%?%[%]%^%$])", "%%%1");
|
||||
return escaped;
|
||||
}
|
||||
|
||||
function DeepCloneTable<T>(src: T, seen?: LuaTable<object, unknown>): T {
|
||||
if (type(src) !== "table") {
|
||||
return src;
|
||||
}
|
||||
const visited = seen ?? new LuaTable<object, unknown>();
|
||||
const existing = visited.get(src as unknown as object);
|
||||
if (existing !== undefined) {
|
||||
return existing as T;
|
||||
}
|
||||
const copy: Record<any, any> = {};
|
||||
visited.set(src as unknown as object, copy);
|
||||
for (const [k, v] of pairs(src as unknown as Record<any, any>)) {
|
||||
copy[DeepCloneTable(k, visited)] = DeepCloneTable(v, visited);
|
||||
}
|
||||
return copy as T;
|
||||
}
|
||||
|
||||
export function RunLua54PitfallsTests(): void {
|
||||
Suite("Extra.Lua54PitfallsAndEdgeCases", () => {
|
||||
Test("Lua truthiness vs JS: explicit checks for 0 and empty string, ?? vs ||", () => {
|
||||
const zero = 0;
|
||||
const empty = "";
|
||||
|
||||
// 在 Lua 中 0 和 "" 均为 truthy!业务代码必须使用显式比较
|
||||
AssertTrue(zero === 0);
|
||||
AssertTrue(empty === "");
|
||||
AssertTrue((zero as unknown as boolean) ? true : false);
|
||||
AssertTrue((empty as unknown as boolean) ? true : false);
|
||||
|
||||
// ?? 在 TSTL 中安全地仅判断 == nil,不会误替换 0 / "" / false
|
||||
const optZero: number | undefined = 0;
|
||||
const optEmpty: string | undefined = "";
|
||||
const optFalse: boolean | undefined = false;
|
||||
const optNil: number | undefined = undefined;
|
||||
|
||||
AssertEqual(optZero ?? 100, 0);
|
||||
AssertEqual(optEmpty ?? "fallback", "");
|
||||
AssertEqual(optFalse ?? true, false);
|
||||
AssertEqual(optNil ?? 100, 100);
|
||||
});
|
||||
|
||||
Test("Lua 5.4 UTF-8 character counting for CJK game text vs byte length", () => {
|
||||
const cnText = "你好UE5世界";
|
||||
// UTF-8 字节数: 4 个汉字 * 3 + 3 ASCII = 15
|
||||
AssertEqual(cnText.length, 15);
|
||||
// utf8.len 返回 Unicode 码点数 = 7
|
||||
const charCount = utf8.len(cnText);
|
||||
AssertEqual(charCount, 7);
|
||||
|
||||
// utf8.codepoint 提取全部码点
|
||||
const codes = [...utf8.codepoint(cnText, 1, -1)];
|
||||
AssertEqual(codes.length, 7);
|
||||
AssertEqual(codes[0], 0x4f60); // '你'
|
||||
AssertEqual(codes[2], 85); // 'U'
|
||||
});
|
||||
|
||||
Test("Lua pattern magic character escaping for literal search & replace", () => {
|
||||
const raw = "Item[Epic]+10 (50.5%)";
|
||||
const escaped = EscapeLuaPattern("[Epic]+10 (50.5%)");
|
||||
const [startIdx] = string.find(raw, escaped);
|
||||
AssertTrue(startIdx !== undefined);
|
||||
|
||||
// 注意:string.gsub 的 replacement 字符串中字面量 % 同样需要转义为 %%
|
||||
const [replaced] = string.gsub(raw, EscapeLuaPattern("(50.5%)"), "(100%%)");
|
||||
AssertEqual(replaced, "Item[Epic]+10 (100%)");
|
||||
});
|
||||
|
||||
Test("0-based TS array vs 1-based UE.TArray interop without sparse holes", () => {
|
||||
const tsArr: string[] = ["first", "second", "third"];
|
||||
const ueArr = UE.TArray<string>(UE.FString);
|
||||
|
||||
for (let i = 0; i < tsArr.length; i++) {
|
||||
ueArr.Add(tsArr[i]);
|
||||
}
|
||||
AssertEqual(ueArr.Length(), tsArr.length);
|
||||
AssertEqual(ueArr.Get(1), tsArr[0]);
|
||||
AssertEqual(ueArr.Get(3), tsArr[2]);
|
||||
|
||||
// Swap-remove O(1) 删除保持紧凑数组无空洞
|
||||
const dense = [10, 20, 30, 40];
|
||||
const removeIdx = 1; // 移除 20
|
||||
dense[removeIdx] = dense[dense.length - 1];
|
||||
table.remove(dense);
|
||||
AssertEqual(dense.length, 3);
|
||||
AssertArrayEqual(dense, [10, 40, 30]);
|
||||
});
|
||||
|
||||
Test("deep clone plain tables safely including circular references", () => {
|
||||
interface Node {
|
||||
name: string;
|
||||
tags: string[];
|
||||
selfRef?: Node;
|
||||
}
|
||||
const original: Node = { name: "Root", tags: ["a", "b"] };
|
||||
original.selfRef = original;
|
||||
|
||||
const cloned = DeepCloneTable(original);
|
||||
AssertEqual(cloned.name, "Root");
|
||||
AssertArrayEqual(cloned.tags, ["a", "b"]);
|
||||
AssertTrue(cloned !== original);
|
||||
AssertTrue(cloned.tags !== original.tags);
|
||||
AssertEqual(cloned.selfRef, cloned);
|
||||
|
||||
cloned.tags.push("c");
|
||||
AssertEqual(original.tags.length, 2);
|
||||
AssertEqual(cloned.tags.length, 3);
|
||||
});
|
||||
|
||||
Test("zero-GC hot-path Tick simulation with cached FVector/FRotator (10,000 frames)", () => {
|
||||
const pos = UE.FVector(0, 0, 0);
|
||||
const vel = UE.FVector(10, 20, -5);
|
||||
const dt = 0.016;
|
||||
|
||||
for (let frame = 0; frame < 10000; frame++) {
|
||||
pos.X += vel.X * dt;
|
||||
pos.Y += vel.Y * dt;
|
||||
pos.Z += vel.Z * dt;
|
||||
}
|
||||
|
||||
AssertNear(pos.X, 1600, 0.1);
|
||||
AssertNear(pos.Y, 3200, 0.1);
|
||||
AssertNear(pos.Z, -800, 0.1);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* 轻量级 AI 行为树(Behavior Tree):支持 Sequence / Selector / Inverter / Cooldown / Condition / Action 与黑板。
|
||||
*/
|
||||
export const enum EBTStatus {
|
||||
Success = 0,
|
||||
Failure = 1,
|
||||
Running = 2,
|
||||
}
|
||||
|
||||
export interface BTBlackboard {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BTContext {
|
||||
dt: number;
|
||||
time: number;
|
||||
bb: BTBlackboard;
|
||||
}
|
||||
|
||||
export interface IBTNode {
|
||||
Tick(ctx: BTContext): EBTStatus;
|
||||
Reset(): void;
|
||||
}
|
||||
|
||||
export class BTCondition implements IBTNode {
|
||||
private check: (this: void, ctx: BTContext) => boolean;
|
||||
|
||||
constructor(check: (this: void, ctx: BTContext) => boolean) {
|
||||
this.check = check;
|
||||
}
|
||||
|
||||
Tick(ctx: BTContext): EBTStatus {
|
||||
return this.check(ctx) ? EBTStatus.Success : EBTStatus.Failure;
|
||||
}
|
||||
|
||||
Reset(): void {}
|
||||
}
|
||||
|
||||
export class BTAction implements IBTNode {
|
||||
private action: (this: void, ctx: BTContext) => EBTStatus;
|
||||
|
||||
constructor(action: (this: void, ctx: BTContext) => EBTStatus) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
Tick(ctx: BTContext): EBTStatus {
|
||||
return this.action(ctx);
|
||||
}
|
||||
|
||||
Reset(): void {}
|
||||
}
|
||||
|
||||
export class BTSequence implements IBTNode {
|
||||
private children: IBTNode[];
|
||||
private runningIndex = 0;
|
||||
|
||||
constructor(children: IBTNode[]) {
|
||||
this.children = children;
|
||||
}
|
||||
|
||||
Tick(ctx: BTContext): EBTStatus {
|
||||
while (this.runningIndex < this.children.length) {
|
||||
const status = this.children[this.runningIndex].Tick(ctx);
|
||||
if (status === EBTStatus.Running) {
|
||||
return EBTStatus.Running;
|
||||
}
|
||||
if (status === EBTStatus.Failure) {
|
||||
this.Reset();
|
||||
return EBTStatus.Failure;
|
||||
}
|
||||
this.runningIndex++;
|
||||
}
|
||||
this.Reset();
|
||||
return EBTStatus.Success;
|
||||
}
|
||||
|
||||
Reset(): void {
|
||||
this.runningIndex = 0;
|
||||
for (let i = 0; i < this.children.length; i++) {
|
||||
this.children[i].Reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class BTSelector implements IBTNode {
|
||||
private children: IBTNode[];
|
||||
private runningIndex = 0;
|
||||
|
||||
constructor(children: IBTNode[]) {
|
||||
this.children = children;
|
||||
}
|
||||
|
||||
Tick(ctx: BTContext): EBTStatus {
|
||||
while (this.runningIndex < this.children.length) {
|
||||
const status = this.children[this.runningIndex].Tick(ctx);
|
||||
if (status === EBTStatus.Running) {
|
||||
return EBTStatus.Running;
|
||||
}
|
||||
if (status === EBTStatus.Success) {
|
||||
this.Reset();
|
||||
return EBTStatus.Success;
|
||||
}
|
||||
this.runningIndex++;
|
||||
}
|
||||
this.Reset();
|
||||
return EBTStatus.Failure;
|
||||
}
|
||||
|
||||
Reset(): void {
|
||||
this.runningIndex = 0;
|
||||
for (let i = 0; i < this.children.length; i++) {
|
||||
this.children[i].Reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class BTInverter implements IBTNode {
|
||||
private child: IBTNode;
|
||||
|
||||
constructor(child: IBTNode) {
|
||||
this.child = child;
|
||||
}
|
||||
|
||||
Tick(ctx: BTContext): EBTStatus {
|
||||
const st = this.child.Tick(ctx);
|
||||
if (st === EBTStatus.Success) return EBTStatus.Failure;
|
||||
if (st === EBTStatus.Failure) return EBTStatus.Success;
|
||||
return EBTStatus.Running;
|
||||
}
|
||||
|
||||
Reset(): void {
|
||||
this.child.Reset();
|
||||
}
|
||||
}
|
||||
|
||||
export class BTCooldown implements IBTNode {
|
||||
private child: IBTNode;
|
||||
private cooldownSeconds: number;
|
||||
private lastSuccessTime = -9999;
|
||||
|
||||
constructor(child: IBTNode, cooldownSeconds: number) {
|
||||
this.child = child;
|
||||
this.cooldownSeconds = cooldownSeconds;
|
||||
}
|
||||
|
||||
Tick(ctx: BTContext): EBTStatus {
|
||||
if (ctx.time - this.lastSuccessTime < this.cooldownSeconds) {
|
||||
return EBTStatus.Failure;
|
||||
}
|
||||
const st = this.child.Tick(ctx);
|
||||
if (st === EBTStatus.Success) {
|
||||
this.lastSuccessTime = ctx.time;
|
||||
}
|
||||
return st;
|
||||
}
|
||||
|
||||
Reset(): void {
|
||||
this.child.Reset();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* RPG 属性修改器、Buff 叠加/周期结算(DoT/HoT)与伤害计算管线。
|
||||
*/
|
||||
export const enum EAttributeId {
|
||||
MaxHP = "MaxHP",
|
||||
HP = "HP",
|
||||
Attack = "Attack",
|
||||
Defense = "Defense",
|
||||
MoveSpeed = "MoveSpeed",
|
||||
}
|
||||
|
||||
export const enum EModifierOp {
|
||||
FlatAdd = 0,
|
||||
PercentMul = 1, // 例如 0.2 表示 +20%
|
||||
}
|
||||
|
||||
export const enum EBuffStackPolicy {
|
||||
RefreshDuration = 0,
|
||||
AddStack = 1,
|
||||
IgnoreIfExists = 2,
|
||||
}
|
||||
|
||||
export interface AttributeModifier {
|
||||
attr: EAttributeId;
|
||||
op: EModifierOp;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface BuffSpec {
|
||||
id: string;
|
||||
duration: number;
|
||||
maxStacks?: number;
|
||||
stackPolicy?: EBuffStackPolicy;
|
||||
modifiers?: AttributeModifier[];
|
||||
tickInterval?: number;
|
||||
hpPerTick?: number; // 正数 HoT,负数 DoT
|
||||
}
|
||||
|
||||
interface ActiveBuff {
|
||||
spec: BuffSpec;
|
||||
stacks: number;
|
||||
remaining: number;
|
||||
tickAccumulator: number;
|
||||
}
|
||||
|
||||
export interface DamageResult {
|
||||
rawDamage: number;
|
||||
mitigatedDamage: number;
|
||||
isCrit: boolean;
|
||||
targetHpAfter: number;
|
||||
targetKilled: boolean;
|
||||
}
|
||||
|
||||
export class AttributeAndBuffComponent {
|
||||
private baseStats: Record<string, number> = {};
|
||||
private buffs: ActiveBuff[] = [];
|
||||
private listeners: ((this: void, attr: EAttributeId, newVal: number) => void)[] = [];
|
||||
|
||||
constructor(initialStats: Record<string, number>) {
|
||||
for (const [k, v] of pairs(initialStats)) {
|
||||
this.baseStats[k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
OnAttributeChanged(cb: (this: void, attr: EAttributeId, newVal: number) => void): void {
|
||||
this.listeners[this.listeners.length] = cb;
|
||||
}
|
||||
|
||||
GetBase(attr: EAttributeId): number {
|
||||
return this.baseStats[attr] ?? 0;
|
||||
}
|
||||
|
||||
SetBase(attr: EAttributeId, val: number): void {
|
||||
let clamped = val;
|
||||
if (attr === EAttributeId.HP) {
|
||||
clamped = math.max(0, math.min(val, this.GetFinal(EAttributeId.MaxHP)));
|
||||
}
|
||||
this.baseStats[attr] = clamped;
|
||||
this.Notify(attr, this.GetFinal(attr));
|
||||
}
|
||||
|
||||
/** 最终值 = (Base + Sum(FlatAdd)) * (1 + Sum(PercentMul)) */
|
||||
GetFinal(attr: EAttributeId): number {
|
||||
const baseVal = this.baseStats[attr] ?? 0;
|
||||
let flat = 0;
|
||||
let pct = 0;
|
||||
for (let i = 0; i < this.buffs.length; i++) {
|
||||
const b = this.buffs[i];
|
||||
const mods = b.spec.modifiers;
|
||||
if (mods === undefined) continue;
|
||||
for (let j = 0; j < mods.length; j++) {
|
||||
const m = mods[j];
|
||||
if (m.attr !== attr) continue;
|
||||
if (m.op === EModifierOp.FlatAdd) {
|
||||
flat += m.value * b.stacks;
|
||||
} else {
|
||||
pct += m.value * b.stacks;
|
||||
}
|
||||
}
|
||||
}
|
||||
return (baseVal + flat) * (1 + pct);
|
||||
}
|
||||
|
||||
ApplyBuff(spec: BuffSpec): void {
|
||||
const policy = spec.stackPolicy ?? EBuffStackPolicy.RefreshDuration;
|
||||
const maxStacks = spec.maxStacks ?? 1;
|
||||
|
||||
for (let i = 0; i < this.buffs.length; i++) {
|
||||
const existing = this.buffs[i];
|
||||
if (existing.spec.id === spec.id) {
|
||||
if (policy === EBuffStackPolicy.IgnoreIfExists) {
|
||||
return;
|
||||
}
|
||||
existing.remaining = spec.duration;
|
||||
if (policy === EBuffStackPolicy.AddStack && existing.stacks < maxStacks) {
|
||||
existing.stacks++;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this.buffs[this.buffs.length] = {
|
||||
spec,
|
||||
stacks: 1,
|
||||
remaining: spec.duration,
|
||||
tickAccumulator: 0,
|
||||
};
|
||||
}
|
||||
|
||||
RemoveBuff(buffId: string): boolean {
|
||||
for (let i = this.buffs.length - 1; i >= 0; i--) {
|
||||
if (this.buffs[i].spec.id === buffId) {
|
||||
table.remove(this.buffs, i + 1);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
GetBuffStacks(buffId: string): number {
|
||||
for (let i = 0; i < this.buffs.length; i++) {
|
||||
if (this.buffs[i].spec.id === buffId) {
|
||||
return this.buffs[i].stacks;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
Tick(dt: number): void {
|
||||
for (let i = this.buffs.length - 1; i >= 0; i--) {
|
||||
const b = this.buffs[i];
|
||||
b.remaining -= dt;
|
||||
|
||||
if (b.spec.tickInterval !== undefined && b.spec.tickInterval > 0 && b.spec.hpPerTick !== undefined) {
|
||||
b.tickAccumulator += dt;
|
||||
while (b.tickAccumulator >= b.spec.tickInterval) {
|
||||
b.tickAccumulator -= b.spec.tickInterval;
|
||||
const delta = b.spec.hpPerTick * b.stacks;
|
||||
this.SetBase(EAttributeId.HP, this.GetBase(EAttributeId.HP) + delta);
|
||||
}
|
||||
}
|
||||
|
||||
if (b.remaining <= 0) {
|
||||
table.remove(this.buffs, i + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 伤害管线:护甲减伤公式 mitigation = 100 / (100 + max(0, def)) */
|
||||
ApplyDamageFrom(
|
||||
attacker: AttributeAndBuffComponent,
|
||||
skillMultiplier: number,
|
||||
isCrit: boolean,
|
||||
critMultiplier = 1.5
|
||||
): DamageResult {
|
||||
const atk = attacker.GetFinal(EAttributeId.Attack);
|
||||
const def = math.max(0, this.GetFinal(EAttributeId.Defense));
|
||||
const raw = atk * skillMultiplier * (isCrit ? critMultiplier : 1.0);
|
||||
const mitigated = math.floor(raw * (100 / (100 + def)) + 0.5);
|
||||
const nextHp = math.max(0, this.GetBase(EAttributeId.HP) - mitigated);
|
||||
this.SetBase(EAttributeId.HP, nextHp);
|
||||
return {
|
||||
rawDamage: raw,
|
||||
mitigatedDamage: mitigated,
|
||||
isCrit,
|
||||
targetHpAfter: nextHp,
|
||||
targetKilled: nextHp <= 0,
|
||||
};
|
||||
}
|
||||
|
||||
private Notify(attr: EAttributeId, val: number): void {
|
||||
for (let i = 0; i < this.listeners.length; i++) {
|
||||
this.listeners[i](attr, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* 基于 Lua 原生 coroutine 的异步任务编排器(替代禁用的 async/await 与 Promise)。
|
||||
* 支持 WaitSeconds、WaitUntil、任务取消,以及可选的 UObject 存活自动取消保护。
|
||||
*/
|
||||
type YieldCommand =
|
||||
| { kind: "wait_seconds"; remaining: number }
|
||||
| { kind: "wait_until"; predicate: (this: void) => boolean };
|
||||
|
||||
interface RunningTask {
|
||||
id: number;
|
||||
co: LuaThread;
|
||||
owner?: UE.UObject;
|
||||
pending?: YieldCommand;
|
||||
cancelled: boolean;
|
||||
}
|
||||
|
||||
export class CoroutineTaskRunner {
|
||||
private nextId = 1;
|
||||
private tasks: RunningTask[] = [];
|
||||
|
||||
Start(body: (this: void) => void, owner?: UE.UObject): number {
|
||||
const id = this.nextId++;
|
||||
const co = coroutine.create(body);
|
||||
const task: RunningTask = {
|
||||
id,
|
||||
co,
|
||||
owner,
|
||||
cancelled: false,
|
||||
};
|
||||
this.tasks[this.tasks.length] = task;
|
||||
this.StepTask(task);
|
||||
return id;
|
||||
}
|
||||
|
||||
Cancel(taskId: number): boolean {
|
||||
for (let i = 0; i < this.tasks.length; i++) {
|
||||
if (this.tasks[i].id === taskId && !this.tasks[i].cancelled) {
|
||||
this.tasks[i].cancelled = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Tick(dt: number): void {
|
||||
const snapshot: RunningTask[] = [];
|
||||
for (let i = 0; i < this.tasks.length; i++) {
|
||||
snapshot[i] = this.tasks[i];
|
||||
}
|
||||
|
||||
for (let i = 0; i < snapshot.length; i++) {
|
||||
const task = snapshot[i];
|
||||
if (task.cancelled || coroutine.status(task.co) === "dead") {
|
||||
task.cancelled = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 若绑定了 UObject,自动检测是否已被销毁
|
||||
if (task.owner !== undefined && !UE.UKismetSystemLibrary.IsValid(task.owner)) {
|
||||
task.cancelled = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
const cmd = task.pending;
|
||||
if (cmd === undefined) {
|
||||
this.StepTask(task);
|
||||
} else if (cmd.kind === "wait_seconds") {
|
||||
cmd.remaining -= dt;
|
||||
if (cmd.remaining <= 0) {
|
||||
task.pending = undefined;
|
||||
this.StepTask(task);
|
||||
}
|
||||
} else if (cmd.kind === "wait_until") {
|
||||
if (cmd.predicate()) {
|
||||
task.pending = undefined;
|
||||
this.StepTask(task);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = this.tasks.length - 1; i >= 0; i--) {
|
||||
const t = this.tasks[i];
|
||||
if (t.cancelled || coroutine.status(t.co) === "dead") {
|
||||
table.remove(this.tasks, i + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GetActiveTaskCount(): number {
|
||||
let count = 0;
|
||||
for (let i = 0; i < this.tasks.length; i++) {
|
||||
const t = this.tasks[i];
|
||||
if (!t.cancelled && coroutine.status(t.co) !== "dead") {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private StepTask(task: RunningTask): void {
|
||||
if (task.cancelled || coroutine.status(task.co) === "dead") {
|
||||
return;
|
||||
}
|
||||
const [ok, yielded] = coroutine.resume(task.co);
|
||||
if (!ok) {
|
||||
task.cancelled = true;
|
||||
error("CoroutineTaskRunner error: " + tostring(yielded));
|
||||
}
|
||||
if (coroutine.status(task.co) === "dead") {
|
||||
task.cancelled = true;
|
||||
} else if (yielded !== undefined) {
|
||||
task.pending = yielded as YieldCommand;
|
||||
}
|
||||
}
|
||||
|
||||
/** 在协程内挂起指定秒数 */
|
||||
static WaitSeconds(this: void, seconds: number): void {
|
||||
const cmd: YieldCommand = { kind: "wait_seconds", remaining: seconds };
|
||||
coroutine.yield(cmd);
|
||||
}
|
||||
|
||||
/** 在协程内挂起直到条件成立 */
|
||||
static WaitUntil(this: void, predicate: (this: void) => boolean): void {
|
||||
if (predicate()) return;
|
||||
const cmd: YieldCommand = { kind: "wait_until", predicate };
|
||||
coroutine.yield(cmd);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* 通用有限状态机(Finite State Machine),适用于角色状态、AI 状态、UI 流程等。
|
||||
*/
|
||||
export interface IStateHandler<TContext> {
|
||||
OnEnter?: (this: void, ctx: TContext, fromState?: string) => void;
|
||||
OnUpdate?: (this: void, ctx: TContext, dt: number) => void;
|
||||
OnExit?: (this: void, ctx: TContext, toState: string) => void;
|
||||
}
|
||||
|
||||
export interface IStateTransition<TContext, TStateId extends string> {
|
||||
from: TStateId | "*";
|
||||
to: TStateId;
|
||||
condition: (this: void, ctx: TContext) => boolean;
|
||||
}
|
||||
|
||||
export class StateMachine<TContext, TStateId extends string> {
|
||||
private ctx: TContext;
|
||||
private states: Record<string, IStateHandler<TContext> | undefined> = {};
|
||||
private transitions: IStateTransition<TContext, TStateId>[] = [];
|
||||
private currentState: TStateId | undefined = undefined;
|
||||
private stateElapsed = 0;
|
||||
private paused = false;
|
||||
private history: TStateId[] = [];
|
||||
|
||||
constructor(ctx: TContext) {
|
||||
this.ctx = ctx;
|
||||
}
|
||||
|
||||
RegisterState(id: TStateId, handler: IStateHandler<TContext>): void {
|
||||
this.states[id] = handler;
|
||||
}
|
||||
|
||||
AddTransition(
|
||||
from: TStateId | "*",
|
||||
to: TStateId,
|
||||
condition: (this: void, ctx: TContext) => boolean
|
||||
): void {
|
||||
this.transitions[this.transitions.length] = { from, to, condition };
|
||||
}
|
||||
|
||||
Start(initialState: TStateId): boolean {
|
||||
if (this.states[initialState] === undefined) {
|
||||
return false;
|
||||
}
|
||||
this.currentState = initialState;
|
||||
this.stateElapsed = 0;
|
||||
this.history[this.history.length] = initialState;
|
||||
const handler = this.states[initialState];
|
||||
if (handler && handler.OnEnter) {
|
||||
handler.OnEnter(this.ctx, undefined);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
ChangeState(nextState: TStateId): boolean {
|
||||
if (this.currentState === nextState || this.states[nextState] === undefined) {
|
||||
return false;
|
||||
}
|
||||
const prev = this.currentState;
|
||||
if (prev !== undefined) {
|
||||
const prevHandler = this.states[prev];
|
||||
if (prevHandler && prevHandler.OnExit) {
|
||||
prevHandler.OnExit(this.ctx, nextState);
|
||||
}
|
||||
}
|
||||
this.currentState = nextState;
|
||||
this.stateElapsed = 0;
|
||||
this.history[this.history.length] = nextState;
|
||||
const nextHandler = this.states[nextState];
|
||||
if (nextHandler && nextHandler.OnEnter) {
|
||||
nextHandler.OnEnter(this.ctx, prev);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Update(dt: number): void {
|
||||
if (this.paused || this.currentState === undefined) {
|
||||
return;
|
||||
}
|
||||
this.stateElapsed += dt;
|
||||
|
||||
// 先检查条件转换
|
||||
for (let i = 0; i < this.transitions.length; i++) {
|
||||
const tr = this.transitions[i];
|
||||
if (
|
||||
(tr.from === "*" || tr.from === this.currentState) &&
|
||||
tr.to !== this.currentState &&
|
||||
tr.condition(this.ctx)
|
||||
) {
|
||||
this.ChangeState(tr.to);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const handler = this.states[this.currentState];
|
||||
if (handler && handler.OnUpdate) {
|
||||
handler.OnUpdate(this.ctx, dt);
|
||||
}
|
||||
}
|
||||
|
||||
SetPaused(paused: boolean): void {
|
||||
this.paused = paused;
|
||||
}
|
||||
|
||||
GetCurrentState(): TStateId | undefined {
|
||||
return this.currentState;
|
||||
}
|
||||
|
||||
GetStateElapsed(): number {
|
||||
return this.stateElapsed;
|
||||
}
|
||||
|
||||
GetHistory(): TStateId[] {
|
||||
return this.history;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
/** @noSelfInFile */
|
||||
|
||||
import {
|
||||
Suite,
|
||||
Test,
|
||||
AssertEqual,
|
||||
AssertNear,
|
||||
AssertTrue,
|
||||
AssertFalse,
|
||||
AssertNil,
|
||||
AssertArrayEqual,
|
||||
} from "../Harness/TestRunner";
|
||||
import { CreateBoundInstance } from "../Harness/MockUnLuaRuntime";
|
||||
import { StateMachine } from "./FSM";
|
||||
import { ObjectPool } from "./ObjectPool";
|
||||
import { TimerScheduler, CooldownTracker } from "./TimerScheduler";
|
||||
import {
|
||||
AttributeAndBuffComponent,
|
||||
EAttributeId,
|
||||
EBuffStackPolicy,
|
||||
EModifierOp,
|
||||
} from "./BuffAndAttributeSystem";
|
||||
import { InventorySystem, EItemRarity } from "./InventorySystem";
|
||||
import { CoroutineTaskRunner } from "./CoroutineTaskRunner";
|
||||
import {
|
||||
BTAction,
|
||||
BTCondition,
|
||||
BTCooldown,
|
||||
BTInverter,
|
||||
BTSelector,
|
||||
BTSequence,
|
||||
BTContext,
|
||||
EBTStatus,
|
||||
} from "./BehaviorTree";
|
||||
|
||||
export function RunGameplayTests(): void {
|
||||
Suite("Gameplay.Systems", () => {
|
||||
Test("FSM: state lifecycle, conditional transitions, pause and history", () => {
|
||||
interface HeroCtx {
|
||||
speed: number;
|
||||
hp: number;
|
||||
log: string[];
|
||||
}
|
||||
type HeroState = "Idle" | "Run" | "Dead";
|
||||
|
||||
const ctx: HeroCtx = { speed: 0, hp: 100, log: [] };
|
||||
const fsm = new StateMachine<HeroCtx, HeroState>(ctx);
|
||||
|
||||
fsm.RegisterState("Idle", {
|
||||
OnEnter: (c) => { c.log[c.log.length] = "Enter:Idle"; },
|
||||
OnExit: (c) => { c.log[c.log.length] = "Exit:Idle"; },
|
||||
});
|
||||
fsm.RegisterState("Run", {
|
||||
OnEnter: (c) => { c.log[c.log.length] = "Enter:Run"; },
|
||||
OnUpdate: (c, dt) => { c.log[c.log.length] = `Run:${math.floor(dt * 100)}`; },
|
||||
});
|
||||
fsm.RegisterState("Dead", {
|
||||
OnEnter: (c) => { c.log[c.log.length] = "Enter:Dead"; },
|
||||
});
|
||||
|
||||
fsm.AddTransition("Idle", "Run", (c) => c.speed > 0);
|
||||
fsm.AddTransition("Run", "Idle", (c) => c.speed === 0);
|
||||
fsm.AddTransition("*", "Dead", (c) => c.hp <= 0);
|
||||
|
||||
AssertTrue(fsm.Start("Idle"));
|
||||
AssertEqual(fsm.GetCurrentState(), "Idle");
|
||||
|
||||
ctx.speed = 300;
|
||||
fsm.Update(0.1);
|
||||
AssertEqual(fsm.GetCurrentState(), "Run");
|
||||
|
||||
fsm.SetPaused(true);
|
||||
ctx.hp = 0;
|
||||
fsm.Update(0.1);
|
||||
AssertEqual(fsm.GetCurrentState(), "Run"); // paused
|
||||
|
||||
fsm.SetPaused(false);
|
||||
fsm.Update(0.1);
|
||||
AssertEqual(fsm.GetCurrentState(), "Dead");
|
||||
AssertArrayEqual(fsm.GetHistory(), ["Idle", "Run", "Dead"]);
|
||||
});
|
||||
|
||||
Test("ObjectPool: prewarm, acquire/reuse, maxCapacity cap and reset hooks", () => {
|
||||
interface Bullet {
|
||||
active: boolean;
|
||||
damage: number;
|
||||
}
|
||||
const pool = new ObjectPool<Bullet>({
|
||||
factory: () => ({ active: false, damage: 0 }),
|
||||
onAcquire: (b) => { b.active = true; b.damage = 10; },
|
||||
onRelease: (b) => { b.active = false; b.damage = 0; },
|
||||
maxCapacity: 2,
|
||||
});
|
||||
|
||||
pool.Prewarm(2);
|
||||
AssertEqual(pool.GetIdleCount(), 2);
|
||||
AssertEqual(pool.GetTotalCreated(), 2);
|
||||
|
||||
const b1 = pool.Acquire();
|
||||
const b2 = pool.Acquire();
|
||||
const b3 = pool.Acquire(); // exceeds prewarm -> creates 3rd
|
||||
AssertTrue(b1.active);
|
||||
AssertEqual(b1.damage, 10);
|
||||
AssertEqual(pool.GetActiveCount(), 3);
|
||||
AssertEqual(pool.GetTotalCreated(), 3);
|
||||
|
||||
pool.Release(b1);
|
||||
pool.Release(b2);
|
||||
pool.Release(b3); // capped at maxCapacity=2
|
||||
AssertFalse(b1.active);
|
||||
AssertEqual(pool.GetActiveCount(), 0);
|
||||
AssertEqual(pool.GetIdleCount(), 2);
|
||||
|
||||
const reused = pool.Acquire();
|
||||
AssertEqual(pool.GetTotalCreated(), 3); // no new allocation
|
||||
AssertTrue(reused.active);
|
||||
});
|
||||
|
||||
Test("TimerScheduler & CooldownTracker: one-shot, repeat, self-cancel, timeScale and cooldowns", () => {
|
||||
const scheduler = new TimerScheduler();
|
||||
const events: string[] = [];
|
||||
|
||||
scheduler.ScheduleOnce(0.5, () => {
|
||||
events[events.length] = "once";
|
||||
});
|
||||
const repId = scheduler.ScheduleRepeat(0.25, (id) => {
|
||||
events[events.length] = `rep#${id}`;
|
||||
}, 3);
|
||||
|
||||
let selfCancelCount = 0;
|
||||
scheduler.ScheduleRepeat(0.2, (id) => {
|
||||
selfCancelCount++;
|
||||
if (selfCancelCount === 2) {
|
||||
scheduler.Cancel(id);
|
||||
}
|
||||
});
|
||||
|
||||
scheduler.Tick(0.5);
|
||||
AssertEqual(selfCancelCount, 2);
|
||||
AssertEqual(events.length, 3); // once + 2 reps (rep at 0.25, 0.5)
|
||||
|
||||
scheduler.SetPaused(repId, true);
|
||||
scheduler.Tick(1.0);
|
||||
AssertEqual(events.length, 3); // paused
|
||||
|
||||
scheduler.SetPaused(repId, false);
|
||||
scheduler.SetTimeScale(0.5);
|
||||
scheduler.Tick(0.5); // effective dt = 0.25 -> 3rd rep fires & finishes
|
||||
AssertEqual(events.length, 4);
|
||||
AssertEqual(scheduler.GetActiveCount(), 0);
|
||||
|
||||
// CooldownTracker
|
||||
const cd = new CooldownTracker();
|
||||
AssertTrue(cd.IsReady("Fireball"));
|
||||
cd.StartCooldown("Fireball", 5.0);
|
||||
AssertFalse(cd.IsReady("Fireball"));
|
||||
cd.Tick(2.0);
|
||||
AssertNear(cd.GetRemaining("Fireball"), 3.0);
|
||||
cd.ReduceCooldown("Fireball", 3.5);
|
||||
AssertTrue(cd.IsReady("Fireball"));
|
||||
AssertEqual(cd.GetRemaining("Fireball"), 0);
|
||||
});
|
||||
|
||||
Test("BuffAndAttributeSystem: flat/percent modifiers, stacking, DoT tick and damage mitigation", () => {
|
||||
const hero = new AttributeAndBuffComponent({
|
||||
[EAttributeId.MaxHP]: 200,
|
||||
[EAttributeId.HP]: 200,
|
||||
[EAttributeId.Attack]: 50,
|
||||
[EAttributeId.Defense]: 0,
|
||||
});
|
||||
const boss = new AttributeAndBuffComponent({
|
||||
[EAttributeId.MaxHP]: 500,
|
||||
[EAttributeId.HP]: 500,
|
||||
[EAttributeId.Attack]: 40,
|
||||
[EAttributeId.Defense]: 100, // 50% damage reduction
|
||||
});
|
||||
|
||||
// 攻击力 Buff: +10 Flat, +20% Mul,叠加 2 层 -> (50 + 20) * 1.4 = 98
|
||||
const furyBuff = {
|
||||
id: "Fury",
|
||||
duration: 5.0,
|
||||
maxStacks: 3,
|
||||
stackPolicy: EBuffStackPolicy.AddStack,
|
||||
modifiers: [
|
||||
{ attr: EAttributeId.Attack, op: EModifierOp.FlatAdd, value: 10 },
|
||||
{ attr: EAttributeId.Attack, op: EModifierOp.PercentMul, value: 0.2 },
|
||||
],
|
||||
};
|
||||
hero.ApplyBuff(furyBuff);
|
||||
hero.ApplyBuff(furyBuff);
|
||||
AssertEqual(hero.GetBuffStacks("Fury"), 2);
|
||||
AssertNear(hero.GetFinal(EAttributeId.Attack), 98);
|
||||
|
||||
// 暴击打击 Boss: raw = 98 * 1.0 * 1.5 = 147, mitigated = round(147 * 100/200) = 74
|
||||
const dmg = boss.ApplyDamageFrom(hero, 1.0, true, 1.5);
|
||||
AssertEqual(dmg.mitigatedDamage, 74);
|
||||
AssertEqual(dmg.targetHpAfter, 426);
|
||||
AssertFalse(dmg.targetKilled);
|
||||
|
||||
// 中毒 DoT: 每 1 秒 -15 HP,持续 3.1 秒
|
||||
boss.ApplyBuff({
|
||||
id: "Poison",
|
||||
duration: 3.1,
|
||||
tickInterval: 1.0,
|
||||
hpPerTick: -15,
|
||||
});
|
||||
boss.Tick(2.5); // 触发 2 次 -> -30 HP -> 396
|
||||
AssertEqual(boss.GetBase(EAttributeId.HP), 396);
|
||||
boss.Tick(1.0); // 触发第 3 次并过期 -> 381
|
||||
AssertEqual(boss.GetBase(EAttributeId.HP), 381);
|
||||
AssertEqual(boss.GetBuffStacks("Poison"), 0);
|
||||
});
|
||||
|
||||
Test("InventorySystem: stack merge, split, swap, consume, filter and serialize/deserialize", () => {
|
||||
const inv = new InventorySystem(4);
|
||||
inv.RegisterItemDef({
|
||||
itemId: "potion_hp",
|
||||
name: "Health Potion",
|
||||
category: "Consumable",
|
||||
rarity: EItemRarity.Common,
|
||||
maxStack: 10,
|
||||
});
|
||||
inv.RegisterItemDef({
|
||||
itemId: "sword_excalibur",
|
||||
name: "Excalibur",
|
||||
category: "Weapon",
|
||||
rarity: EItemRarity.Legendary,
|
||||
maxStack: 1,
|
||||
});
|
||||
|
||||
// 添加 25 瓶药水 -> 占 3 格 (10, 10, 5)
|
||||
AssertEqual(inv.AddItem("potion_hp", 25), 0);
|
||||
AssertEqual(inv.GetItemCount("potion_hp"), 25);
|
||||
AssertEqual(inv.GetUsedSlotCount(), 3);
|
||||
|
||||
// 添加 2 把不可堆叠武器 -> 第 1 把占第 4 格,第 2 把放不下返回 overflow=1
|
||||
AssertEqual(inv.AddItem("sword_excalibur", 2), 1);
|
||||
AssertEqual(inv.GetItemCount("sword_excalibur"), 1);
|
||||
|
||||
// 消耗 12 瓶药水 -> 剩 13 瓶 (10, 3),释放 1 个空格
|
||||
AssertTrue(inv.ConsumeItem("potion_hp", 12));
|
||||
AssertEqual(inv.GetItemCount("potion_hp"), 13);
|
||||
AssertNil(inv.GetSlot(2));
|
||||
|
||||
// 拆分第 0 格 (10 -> 6 + 4 放入第 2 格)
|
||||
AssertTrue(inv.SplitSlot(0, 2, 4));
|
||||
AssertEqual(inv.GetSlot(0)!.count, 6);
|
||||
AssertEqual(inv.GetSlot(2)!.count, 4);
|
||||
|
||||
// 交换格子 & 按类别筛选(此时 slot 0=武器,slot 1/2/3=药水共 3 格)
|
||||
AssertTrue(inv.SwapSlots(0, 3));
|
||||
AssertEqual(inv.GetSlot(0)!.itemId, "sword_excalibur");
|
||||
AssertEqual(inv.FilterByCategory("Weapon").length, 1);
|
||||
AssertEqual(inv.FilterByCategory("Consumable").length, 3);
|
||||
|
||||
// 序列化与反序列化
|
||||
const saved = inv.Serialize();
|
||||
const restored = new InventorySystem(1);
|
||||
restored.Deserialize(saved);
|
||||
AssertEqual(restored.GetItemCount("potion_hp"), 13);
|
||||
AssertEqual(restored.GetSlot(0)!.itemId, "sword_excalibur");
|
||||
});
|
||||
|
||||
Test("CoroutineTaskRunner: WaitSeconds, WaitUntil and UObject destroy auto-cancellation", () => {
|
||||
const runner = new CoroutineTaskRunner();
|
||||
const trace: string[] = [];
|
||||
let doorOpened = false;
|
||||
|
||||
runner.Start(() => {
|
||||
trace[trace.length] = "start";
|
||||
CoroutineTaskRunner.WaitSeconds(0.5);
|
||||
trace[trace.length] = "after_delay";
|
||||
CoroutineTaskRunner.WaitUntil(() => doorOpened);
|
||||
trace[trace.length] = "entered_room";
|
||||
});
|
||||
|
||||
AssertArrayEqual(trace, ["start"]);
|
||||
runner.Tick(0.3);
|
||||
AssertArrayEqual(trace, ["start"]);
|
||||
runner.Tick(0.3);
|
||||
AssertArrayEqual(trace, ["start", "after_delay"]);
|
||||
runner.Tick(1.0);
|
||||
AssertArrayEqual(trace, ["start", "after_delay"]); // still waiting for door
|
||||
|
||||
doorOpened = true;
|
||||
runner.Tick(0.016);
|
||||
AssertArrayEqual(trace, ["start", "after_delay", "entered_room"]);
|
||||
AssertEqual(runner.GetActiveTaskCount(), 0);
|
||||
|
||||
// 绑定 UObject 存活自动取消测试
|
||||
const ownerActor = CreateBoundInstance<UE.AActor>({}, "AActor");
|
||||
let postDestroyExecuted = false;
|
||||
runner.Start(() => {
|
||||
CoroutineTaskRunner.WaitSeconds(1.0);
|
||||
postDestroyExecuted = true;
|
||||
}, ownerActor);
|
||||
|
||||
ownerActor.K2_DestroyActor();
|
||||
runner.Tick(2.0);
|
||||
AssertFalse(postDestroyExecuted);
|
||||
AssertEqual(runner.GetActiveTaskCount(), 0);
|
||||
});
|
||||
|
||||
Test("BehaviorTree: Selector/Sequence/Cooldown/Inverter with Running resumption", () => {
|
||||
const log: string[] = [];
|
||||
let castProgress = 0;
|
||||
|
||||
const castUltimate = new BTCooldown(
|
||||
new BTSequence([
|
||||
new BTCondition((ctx) => (ctx.bb["mana"] as number) >= 50),
|
||||
new BTAction((ctx) => {
|
||||
castProgress += ctx.dt;
|
||||
if (castProgress < 1.0) {
|
||||
log[log.length] = "casting";
|
||||
return EBTStatus.Running;
|
||||
}
|
||||
castProgress = 0;
|
||||
ctx.bb["mana"] = (ctx.bb["mana"] as number) - 50;
|
||||
log[log.length] = "ult_fired";
|
||||
return EBTStatus.Success;
|
||||
}),
|
||||
]),
|
||||
5.0
|
||||
);
|
||||
|
||||
const basicAttack = new BTSequence([
|
||||
new BTInverter(new BTCondition((ctx) => ctx.bb["stunned"] === true)),
|
||||
new BTAction(() => {
|
||||
log[log.length] = "basic_attack";
|
||||
return EBTStatus.Success;
|
||||
}),
|
||||
]);
|
||||
|
||||
const root = new BTSelector([castUltimate, basicAttack]);
|
||||
const ctx: BTContext = {
|
||||
dt: 0.5,
|
||||
time: 0,
|
||||
bb: { mana: 60, stunned: false },
|
||||
};
|
||||
|
||||
// t=0: 开始施放终极技能 -> Running
|
||||
AssertEqual(root.Tick(ctx), EBTStatus.Running);
|
||||
// t=0.5: 继续施放并完成 -> Success, 进入 5 秒冷却
|
||||
ctx.time = 0.5;
|
||||
AssertEqual(root.Tick(ctx), EBTStatus.Success);
|
||||
AssertEqual(ctx.bb["mana"], 10);
|
||||
|
||||
// t=1.0: 终极技能冷却中 -> 回退到普通攻击
|
||||
ctx.time = 1.0;
|
||||
AssertEqual(root.Tick(ctx), EBTStatus.Success);
|
||||
|
||||
// t=1.5: 被眩晕 -> 全部失败
|
||||
ctx.time = 1.5;
|
||||
ctx.bb["stunned"] = true;
|
||||
AssertEqual(root.Tick(ctx), EBTStatus.Failure);
|
||||
|
||||
AssertArrayEqual(log, ["casting", "ult_fired", "basic_attack"]);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* 格子背包系统:支持堆叠合并、拆分、交换、消耗、标签过滤与纯 Lua 表序列化/反序列化。
|
||||
*/
|
||||
export const enum EItemRarity {
|
||||
Common = 0,
|
||||
Rare = 1,
|
||||
Epic = 2,
|
||||
Legendary = 3,
|
||||
}
|
||||
|
||||
export interface ItemDef {
|
||||
itemId: string;
|
||||
name: string;
|
||||
category: "Weapon" | "Consumable" | "Material";
|
||||
rarity: EItemRarity;
|
||||
maxStack: number;
|
||||
}
|
||||
|
||||
export interface InventorySlot {
|
||||
itemId: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface SerializedInventory {
|
||||
capacity: number;
|
||||
slots: Record<number, InventorySlot>;
|
||||
}
|
||||
|
||||
export class InventorySystem {
|
||||
private capacity: number;
|
||||
private defs: Record<string, ItemDef | undefined> = {};
|
||||
private slots: Record<number, InventorySlot | undefined> = {};
|
||||
|
||||
constructor(capacity: number) {
|
||||
this.capacity = capacity;
|
||||
}
|
||||
|
||||
RegisterItemDef(def: ItemDef): void {
|
||||
this.defs[def.itemId] = def;
|
||||
}
|
||||
|
||||
/** 添加物品,返回未放下的剩余数量(0 表示全部成功放入) */
|
||||
AddItem(itemId: string, amount: number): number {
|
||||
const def = this.defs[itemId];
|
||||
if (def === undefined || amount <= 0) {
|
||||
return amount;
|
||||
}
|
||||
let remaining = amount;
|
||||
|
||||
// 1. 先合并到已有未满堆叠格
|
||||
for (let i = 0; i < this.capacity && remaining > 0; i++) {
|
||||
const slot = this.slots[i];
|
||||
if (slot !== undefined && slot.itemId === itemId && slot.count < def.maxStack) {
|
||||
const space = def.maxStack - slot.count;
|
||||
const add = math.min(space, remaining);
|
||||
slot.count += add;
|
||||
remaining -= add;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 放入空格子
|
||||
for (let i = 0; i < this.capacity && remaining > 0; i++) {
|
||||
if (this.slots[i] === undefined) {
|
||||
const add = math.min(def.maxStack, remaining);
|
||||
this.slots[i] = { itemId, count: add };
|
||||
remaining -= add;
|
||||
}
|
||||
}
|
||||
|
||||
return remaining;
|
||||
}
|
||||
|
||||
ConsumeItem(itemId: string, amount: number): boolean {
|
||||
if (amount <= 0 || this.GetItemCount(itemId) < amount) {
|
||||
return false;
|
||||
}
|
||||
let remaining = amount;
|
||||
for (let i = this.capacity - 1; i >= 0 && remaining > 0; i--) {
|
||||
const slot = this.slots[i];
|
||||
if (slot !== undefined && slot.itemId === itemId) {
|
||||
const take = math.min(slot.count, remaining);
|
||||
slot.count -= take;
|
||||
remaining -= take;
|
||||
if (slot.count <= 0) {
|
||||
this.slots[i] = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
SwapSlots(slotA: number, slotB: number): boolean {
|
||||
if (slotA < 0 || slotA >= this.capacity || slotB < 0 || slotB >= this.capacity) {
|
||||
return false;
|
||||
}
|
||||
const tmp = this.slots[slotA];
|
||||
this.slots[slotA] = this.slots[slotB];
|
||||
this.slots[slotB] = tmp;
|
||||
return true;
|
||||
}
|
||||
|
||||
SplitSlot(fromSlot: number, toSlot: number, splitCount: number): boolean {
|
||||
if (
|
||||
fromSlot < 0 ||
|
||||
fromSlot >= this.capacity ||
|
||||
toSlot < 0 ||
|
||||
toSlot >= this.capacity ||
|
||||
fromSlot === toSlot
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const src = this.slots[fromSlot];
|
||||
if (src === undefined || this.slots[toSlot] !== undefined) {
|
||||
return false;
|
||||
}
|
||||
if (splitCount <= 0 || splitCount >= src.count) {
|
||||
return false;
|
||||
}
|
||||
src.count -= splitCount;
|
||||
this.slots[toSlot] = { itemId: src.itemId, count: splitCount };
|
||||
return true;
|
||||
}
|
||||
|
||||
GetItemCount(itemId: string): number {
|
||||
let total = 0;
|
||||
for (let i = 0; i < this.capacity; i++) {
|
||||
const slot = this.slots[i];
|
||||
if (slot !== undefined && slot.itemId === itemId) {
|
||||
total += slot.count;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
GetSlot(index: number): InventorySlot | undefined {
|
||||
return this.slots[index];
|
||||
}
|
||||
|
||||
GetUsedSlotCount(): number {
|
||||
let used = 0;
|
||||
for (let i = 0; i < this.capacity; i++) {
|
||||
if (this.slots[i] !== undefined) used++;
|
||||
}
|
||||
return used;
|
||||
}
|
||||
|
||||
FilterByCategory(category: ItemDef["category"]): InventorySlot[] {
|
||||
const out: InventorySlot[] = [];
|
||||
for (let i = 0; i < this.capacity; i++) {
|
||||
const slot = this.slots[i];
|
||||
if (slot !== undefined) {
|
||||
const def = this.defs[slot.itemId];
|
||||
if (def !== undefined && def.category === category) {
|
||||
out[out.length] = slot;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Serialize(): SerializedInventory {
|
||||
const copiedSlots: Record<number, InventorySlot> = {};
|
||||
for (let i = 0; i < this.capacity; i++) {
|
||||
const s = this.slots[i];
|
||||
if (s !== undefined) {
|
||||
copiedSlots[i] = { itemId: s.itemId, count: s.count };
|
||||
}
|
||||
}
|
||||
return {
|
||||
capacity: this.capacity,
|
||||
slots: copiedSlots,
|
||||
};
|
||||
}
|
||||
|
||||
Deserialize(data: SerializedInventory): void {
|
||||
this.capacity = data.capacity;
|
||||
this.slots = {};
|
||||
for (const [idx, s] of pairs(data.slots)) {
|
||||
this.slots[idx] = { itemId: s.itemId, count: s.count };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* 通用对象池(Object Pool),减少高频创建/销毁(子弹、特效、伤害飘字等)的 GC 压力。
|
||||
*/
|
||||
export interface IObjectPoolOptions<T> {
|
||||
factory: (this: void) => T;
|
||||
onAcquire?: (this: void, obj: T) => void;
|
||||
onRelease?: (this: void, obj: T) => void;
|
||||
maxCapacity?: number;
|
||||
}
|
||||
|
||||
export class ObjectPool<T> {
|
||||
private factory: (this: void) => T;
|
||||
private onAcquire?: (this: void, obj: T) => void;
|
||||
private onRelease?: (this: void, obj: T) => void;
|
||||
private maxCapacity: number;
|
||||
private idle: T[] = [];
|
||||
private activeCount = 0;
|
||||
private totalCreated = 0;
|
||||
|
||||
constructor(options: IObjectPoolOptions<T>) {
|
||||
this.factory = options.factory;
|
||||
this.onAcquire = options.onAcquire;
|
||||
this.onRelease = options.onRelease;
|
||||
this.maxCapacity = options.maxCapacity ?? 64;
|
||||
}
|
||||
|
||||
Prewarm(count: number): void {
|
||||
const target = math.min(count, this.maxCapacity);
|
||||
while (this.idle.length < target) {
|
||||
this.totalCreated++;
|
||||
this.idle[this.idle.length] = this.factory();
|
||||
}
|
||||
}
|
||||
|
||||
Acquire(): T {
|
||||
let obj: T;
|
||||
if (this.idle.length > 0) {
|
||||
obj = table.remove(this.idle) as T;
|
||||
} else {
|
||||
this.totalCreated++;
|
||||
obj = this.factory();
|
||||
}
|
||||
this.activeCount++;
|
||||
if (this.onAcquire) {
|
||||
this.onAcquire(obj);
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
Release(obj: T): void {
|
||||
if (this.activeCount > 0) {
|
||||
this.activeCount--;
|
||||
}
|
||||
if (this.onRelease) {
|
||||
this.onRelease(obj);
|
||||
}
|
||||
if (this.idle.length < this.maxCapacity) {
|
||||
this.idle[this.idle.length] = obj;
|
||||
}
|
||||
}
|
||||
|
||||
Clear(): void {
|
||||
this.idle = [];
|
||||
this.activeCount = 0;
|
||||
}
|
||||
|
||||
GetIdleCount(): number {
|
||||
return this.idle.length;
|
||||
}
|
||||
|
||||
GetActiveCount(): number {
|
||||
return this.activeCount;
|
||||
}
|
||||
|
||||
GetTotalCreated(): number {
|
||||
return this.totalCreated;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* 帧驱动定时器调度器与技能冷却追踪器(零 JS polyfill,回调中支持安全取消/新增)。
|
||||
*/
|
||||
interface ScheduledTimer {
|
||||
id: number;
|
||||
interval: number;
|
||||
remaining: number;
|
||||
maxRepeats: number; // 0 = infinite
|
||||
firedCount: number;
|
||||
paused: boolean;
|
||||
cancelled: boolean;
|
||||
callback: (this: void, handleId: number) => void;
|
||||
}
|
||||
|
||||
export class TimerScheduler {
|
||||
private nextId = 1;
|
||||
private timers: ScheduledTimer[] = [];
|
||||
private timeScale = 1.0;
|
||||
|
||||
ScheduleOnce(delay: number, callback: (this: void, handleId: number) => void): number {
|
||||
return this.AddTimer(delay, 1, callback);
|
||||
}
|
||||
|
||||
ScheduleRepeat(
|
||||
interval: number,
|
||||
callback: (this: void, handleId: number) => void,
|
||||
maxRepeats = 0
|
||||
): number {
|
||||
return this.AddTimer(interval, maxRepeats, callback);
|
||||
}
|
||||
|
||||
private AddTimer(
|
||||
interval: number,
|
||||
maxRepeats: number,
|
||||
callback: (this: void, handleId: number) => void
|
||||
): number {
|
||||
const id = this.nextId++;
|
||||
const safeInterval = math.max(0.0001, interval);
|
||||
this.timers[this.timers.length] = {
|
||||
id,
|
||||
interval: safeInterval,
|
||||
remaining: safeInterval,
|
||||
maxRepeats,
|
||||
firedCount: 0,
|
||||
paused: false,
|
||||
cancelled: false,
|
||||
callback,
|
||||
};
|
||||
return id;
|
||||
}
|
||||
|
||||
Cancel(handleId: number): boolean {
|
||||
for (let i = 0; i < this.timers.length; i++) {
|
||||
if (this.timers[i].id === handleId && !this.timers[i].cancelled) {
|
||||
this.timers[i].cancelled = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
SetPaused(handleId: number, paused: boolean): void {
|
||||
for (let i = 0; i < this.timers.length; i++) {
|
||||
if (this.timers[i].id === handleId) {
|
||||
this.timers[i].paused = paused;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SetTimeScale(scale: number): void {
|
||||
this.timeScale = math.max(0, scale);
|
||||
}
|
||||
|
||||
Tick(dt: number): void {
|
||||
const scaledDt = dt * this.timeScale;
|
||||
if (scaledDt <= 0) return;
|
||||
|
||||
// 快照遍历,避免回调内增删影响当前帧
|
||||
const snapshot: ScheduledTimer[] = [];
|
||||
for (let i = 0; i < this.timers.length; i++) {
|
||||
snapshot[i] = this.timers[i];
|
||||
}
|
||||
|
||||
for (let i = 0; i < snapshot.length; i++) {
|
||||
const t = snapshot[i];
|
||||
if (t.cancelled || t.paused) continue;
|
||||
t.remaining -= scaledDt;
|
||||
while (!t.cancelled && !t.paused && t.remaining <= 0) {
|
||||
t.firedCount++;
|
||||
t.callback(t.id);
|
||||
if (t.maxRepeats > 0 && t.firedCount >= t.maxRepeats) {
|
||||
t.cancelled = true;
|
||||
break;
|
||||
}
|
||||
t.remaining += t.interval;
|
||||
}
|
||||
}
|
||||
|
||||
// 统一清理已完成或已取消的定时器
|
||||
for (let i = this.timers.length - 1; i >= 0; i--) {
|
||||
if (this.timers[i].cancelled) {
|
||||
table.remove(this.timers, i + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GetActiveCount(): number {
|
||||
let count = 0;
|
||||
for (let i = 0; i < this.timers.length; i++) {
|
||||
if (!this.timers[i].cancelled) count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
export class CooldownTracker {
|
||||
private remainingMap: Record<string, number | undefined> = {};
|
||||
|
||||
StartCooldown(skillId: string, duration: number): void {
|
||||
if (duration > 0) {
|
||||
this.remainingMap[skillId] = duration;
|
||||
}
|
||||
}
|
||||
|
||||
IsReady(skillId: string): boolean {
|
||||
const rem = this.remainingMap[skillId];
|
||||
return rem === undefined || rem <= 0;
|
||||
}
|
||||
|
||||
GetRemaining(skillId: string): number {
|
||||
return this.remainingMap[skillId] ?? 0;
|
||||
}
|
||||
|
||||
ReduceCooldown(skillId: string, seconds: number): void {
|
||||
const rem = this.remainingMap[skillId];
|
||||
if (rem !== undefined) {
|
||||
const next = rem - seconds;
|
||||
this.remainingMap[skillId] = next > 0 ? next : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
Tick(dt: number): void {
|
||||
for (const [skillId, rem] of pairs(this.remainingMap)) {
|
||||
if (rem !== undefined) {
|
||||
const next = rem - dt;
|
||||
this.remainingMap[skillId] = next > 0 ? next : undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,172 @@
|
||||
/** @noSelfInFile */
|
||||
|
||||
export interface TestCaseResult {
|
||||
suite: string;
|
||||
name: string;
|
||||
passed: boolean;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
export interface SuiteSummary {
|
||||
total: number;
|
||||
passed: number;
|
||||
failed: number;
|
||||
results: TestCaseResult[];
|
||||
}
|
||||
|
||||
let currentSuite = "Default";
|
||||
let results: TestCaseResult[] = [];
|
||||
|
||||
export function Reset(): void {
|
||||
currentSuite = "Default";
|
||||
results = [];
|
||||
}
|
||||
|
||||
export function Suite(name: string, body: (this: void) => void): void {
|
||||
const prev = currentSuite;
|
||||
currentSuite = name;
|
||||
body();
|
||||
currentSuite = prev;
|
||||
}
|
||||
|
||||
export function Test(name: string, fn: (this: void) => void): void {
|
||||
const [ok, err] = pcall(fn);
|
||||
if (ok) {
|
||||
results[results.length] = {
|
||||
suite: currentSuite,
|
||||
name,
|
||||
passed: true,
|
||||
};
|
||||
} else {
|
||||
results[results.length] = {
|
||||
suite: currentSuite,
|
||||
name,
|
||||
passed: false,
|
||||
errorMessage: tostring(err),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function AssertTrue(cond: unknown, msg?: string): void {
|
||||
if (!cond) {
|
||||
error(msg ?? "Expected condition to be truthy", 2);
|
||||
}
|
||||
}
|
||||
|
||||
export function AssertFalse(cond: unknown, msg?: string): void {
|
||||
if (cond) {
|
||||
error(msg ?? "Expected condition to be falsy", 2);
|
||||
}
|
||||
}
|
||||
|
||||
export function AssertEqual<T>(actual: T, expected: T, msg?: string): void {
|
||||
if (actual !== expected) {
|
||||
const prefix = msg ? `${msg}: ` : "";
|
||||
error(
|
||||
string.format("%sExpected %s, got %s", prefix, tostring(expected), tostring(actual)),
|
||||
2
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function AssertNear(actual: number, expected: number, epsilon = 1e-4, msg?: string): void {
|
||||
if (math.abs(actual - expected) > epsilon) {
|
||||
const prefix = msg ? `${msg}: ` : "";
|
||||
error(
|
||||
string.format(
|
||||
"%sExpected %.6f (±%.6f), got %.6f",
|
||||
prefix,
|
||||
expected,
|
||||
epsilon,
|
||||
actual
|
||||
),
|
||||
2
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function AssertNil(value: unknown, msg?: string): void {
|
||||
if (value !== undefined) {
|
||||
const prefix = msg ? `${msg}: ` : "";
|
||||
error(string.format("%sExpected nil, got %s", prefix, tostring(value)), 2);
|
||||
}
|
||||
}
|
||||
|
||||
export function AssertNotNil(value: unknown, msg?: string): void {
|
||||
if (value === undefined) {
|
||||
error(msg ?? "Expected non-nil value", 2);
|
||||
}
|
||||
}
|
||||
|
||||
export function AssertArrayEqual<T>(actual: T[], expected: T[], msg?: string): void {
|
||||
const prefix = msg ? `${msg}: ` : "";
|
||||
if (actual.length !== expected.length) {
|
||||
error(
|
||||
string.format(
|
||||
"%sArray length mismatch: expected %d, got %d",
|
||||
prefix,
|
||||
expected.length,
|
||||
actual.length
|
||||
),
|
||||
2
|
||||
);
|
||||
}
|
||||
for (let i = 0; i < expected.length; i++) {
|
||||
if (actual[i] !== expected[i]) {
|
||||
error(
|
||||
string.format(
|
||||
"%sArray element [%d] mismatch: expected %s, got %s",
|
||||
prefix,
|
||||
i,
|
||||
tostring(expected[i]),
|
||||
tostring(actual[i])
|
||||
),
|
||||
2
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function GetSummary(): SuiteSummary {
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
for (let i = 0; i < results.length; i++) {
|
||||
if (results[i].passed) {
|
||||
passed++;
|
||||
} else {
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
return {
|
||||
total: results.length,
|
||||
passed,
|
||||
failed,
|
||||
results,
|
||||
};
|
||||
}
|
||||
|
||||
export function PrintReport(): SuiteSummary {
|
||||
const summary = GetSummary();
|
||||
let lastSuite = "";
|
||||
for (let i = 0; i < summary.results.length; i++) {
|
||||
const r = summary.results[i];
|
||||
if (r.suite !== lastSuite) {
|
||||
lastSuite = r.suite;
|
||||
print(string.format("\n[%s]", r.suite));
|
||||
}
|
||||
if (r.passed) {
|
||||
print(string.format(" PASS %s", r.name));
|
||||
} else {
|
||||
print(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
|
||||
)
|
||||
);
|
||||
return summary;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/** @noSelfInFile */
|
||||
|
||||
import { Reset, PrintReport, SuiteSummary } from "./Harness/TestRunner";
|
||||
import { InstallIfNeeded } from "./Harness/MockUnLuaRuntime";
|
||||
import { RunBasicTypesAndControlFlowTests } from "./Syntax/BasicTypesAndControlFlow";
|
||||
import { RunFunctionsClosuresAndTuplesTests } from "./Syntax/FunctionsClosuresAndTuples";
|
||||
import { RunPureClassesAndGenericsTests } from "./Syntax/PureClassesAndGenerics";
|
||||
import { RunUnLuaSyntaxTests } from "./Syntax/UnLuaSyntaxSuite";
|
||||
import { RunUnLuaExamplesTests } from "./UnLuaExamples/UnLuaExamplesSuite";
|
||||
import { RunGameplayTests } from "./Gameplay/GameplaySuite";
|
||||
import { RunHotReloadAndFrameworkTests } from "./Extra/HotReloadAndFrameworkTest";
|
||||
import { RunLua54PitfallsTests } from "./Extra/Lua54PitfallsTest";
|
||||
import { RunLifecycleAndMemoryTests } from "./Extra/LifecycleAndMemoryTest";
|
||||
|
||||
export function RunAll(): SuiteSummary {
|
||||
InstallIfNeeded();
|
||||
Reset();
|
||||
|
||||
// 1. ts2lua 语法与 @unlua 特性测试
|
||||
RunBasicTypesAndControlFlowTests();
|
||||
RunFunctionsClosuresAndTuplesTests();
|
||||
RunPureClassesAndGenericsTests();
|
||||
RunUnLuaSyntaxTests();
|
||||
|
||||
// 2. UnLua 官方示例 TS 实现测试(Ex01 ~ Ex09)
|
||||
RunUnLuaExamplesTests();
|
||||
|
||||
// 3. 常用游戏开发功能 TS 实现测试
|
||||
RunGameplayTests();
|
||||
|
||||
// 4. 补充测试:框架集成、热重载、Lua 5.4 陷阱与生命周期安全
|
||||
RunHotReloadAndFrameworkTests();
|
||||
RunLua54PitfallsTests();
|
||||
RunLifecycleAndMemoryTests();
|
||||
|
||||
return PrintReport();
|
||||
}
|
||||
|
||||
// 当作为脚本由 `lua5.4` 直接执行时自动运行并返回标准退出码
|
||||
const g = _G as unknown as Record<string, any>;
|
||||
if (g.__TS2LUA_TEST_AUTO_RUN__ === true) {
|
||||
const summary = RunAll();
|
||||
if (summary.failed > 0) {
|
||||
os.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
/** @noSelfInFile */
|
||||
|
||||
import {
|
||||
Suite,
|
||||
Test,
|
||||
AssertEqual,
|
||||
AssertNear,
|
||||
AssertTrue,
|
||||
AssertFalse,
|
||||
AssertNil,
|
||||
AssertArrayEqual,
|
||||
} from "../Harness/TestRunner";
|
||||
|
||||
const enum EBitFlag {
|
||||
None = 0,
|
||||
Move = 1 << 0,
|
||||
Jump = 1 << 1,
|
||||
Attack = 1 << 2,
|
||||
Stunned = 1 << 3,
|
||||
}
|
||||
|
||||
const enum ERoleName {
|
||||
Tank = "Tank",
|
||||
Healer = "Healer",
|
||||
DPS = "DPS",
|
||||
}
|
||||
|
||||
type CommandAction =
|
||||
| { kind: "move"; x: number; y: number }
|
||||
| { kind: "damage"; amount: number; crit: boolean }
|
||||
| { kind: "noop" };
|
||||
|
||||
function EvaluateCommand(action: CommandAction): number {
|
||||
switch (action.kind) {
|
||||
case "move":
|
||||
return action.x + action.y;
|
||||
case "damage":
|
||||
return action.crit ? action.amount * 2 : action.amount;
|
||||
case "noop":
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export function RunBasicTypesAndControlFlowTests(): void {
|
||||
Suite("Syntax.BasicTypesAndControlFlow", () => {
|
||||
Test("primitives, template literals, nullish coalescing and optional chaining", () => {
|
||||
const count = 42;
|
||||
const ratio = 0.5;
|
||||
// Lua 5.4 中浮点运算结果转为字符串带 ".0",需要整数格式时用 math.floor 或 string.format("%d")
|
||||
const label = `Count=${count},Half=${math.floor(count * ratio)}`;
|
||||
AssertEqual(label, "Count=42,Half=21");
|
||||
AssertEqual(`${count * ratio}`, "21.0");
|
||||
|
||||
const maybeNum: number | undefined = undefined;
|
||||
const zeroNum: number | undefined = 0;
|
||||
const falseFlag: boolean | undefined = false;
|
||||
|
||||
// ?? 只在 nil/undefined 时回退,不吞 0 和 false
|
||||
AssertEqual(maybeNum ?? 99, 99);
|
||||
AssertEqual(zeroNum ?? 99, 0);
|
||||
AssertEqual(falseFlag ?? true, false);
|
||||
|
||||
interface NestedCfg {
|
||||
inner?: { value?: number };
|
||||
}
|
||||
const a: NestedCfg = {};
|
||||
const b: NestedCfg = { inner: { value: 7 } };
|
||||
AssertNil(a.inner?.value);
|
||||
AssertEqual(b.inner?.value ?? -1, 7);
|
||||
});
|
||||
|
||||
Test("Lua 5.4 native bitwise operators and const enum inlining", () => {
|
||||
let flags: number = EBitFlag.None;
|
||||
flags = flags | EBitFlag.Move | EBitFlag.Attack;
|
||||
AssertTrue((flags & EBitFlag.Move) !== 0);
|
||||
AssertFalse((flags & EBitFlag.Jump) !== 0);
|
||||
AssertTrue((flags & EBitFlag.Attack) !== 0);
|
||||
|
||||
// 清除 Attack,切换 Jump
|
||||
flags = flags & ~EBitFlag.Attack;
|
||||
flags = flags ^ EBitFlag.Jump;
|
||||
AssertFalse((flags & EBitFlag.Attack) !== 0);
|
||||
AssertTrue((flags & EBitFlag.Jump) !== 0);
|
||||
|
||||
// 位移运算(Lua 5.4 原生右移为逻辑右移,TSTL 要求使用 >>>)
|
||||
AssertEqual(1 << 4, 16);
|
||||
AssertEqual(64 >>> 2, 16);
|
||||
|
||||
// 字符串 const enum 内联
|
||||
const role: string = ERoleName.Healer;
|
||||
AssertEqual(role, "Healer");
|
||||
});
|
||||
|
||||
Test("control flow: switch/case fallthrough, loops, continue, break, labeled loop", () => {
|
||||
const Classify = (n: number): string => {
|
||||
switch (n) {
|
||||
case 1:
|
||||
case 2:
|
||||
return "small";
|
||||
case 3:
|
||||
return "medium";
|
||||
default:
|
||||
return "large";
|
||||
}
|
||||
};
|
||||
AssertEqual(Classify(1), "small");
|
||||
AssertEqual(Classify(2), "small");
|
||||
AssertEqual(Classify(3), "medium");
|
||||
AssertEqual(Classify(9), "large");
|
||||
|
||||
// while + continue + break
|
||||
let sum = 0;
|
||||
let i = 0;
|
||||
while (i < 10) {
|
||||
i++;
|
||||
if (i % 2 === 0) continue;
|
||||
if (i > 7) break;
|
||||
sum += i; // 1 + 3 + 5 + 7 = 16
|
||||
}
|
||||
AssertEqual(sum, 16);
|
||||
|
||||
// do-while 至少执行一次
|
||||
let doCount = 0;
|
||||
do {
|
||||
doCount++;
|
||||
} while (false);
|
||||
AssertEqual(doCount, 1);
|
||||
|
||||
// 嵌套循环提前退出(TSTL 不支持 LabeledStatement,使用标志位退出)
|
||||
let foundPair = "";
|
||||
let found = false;
|
||||
for (let r = 0; r < 5 && !found; r++) {
|
||||
for (let c = 0; c < 5; c++) {
|
||||
if (r * 10 + c === 23) {
|
||||
foundPair = `${r},${c}`;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
AssertEqual(foundPair, "2,3");
|
||||
});
|
||||
|
||||
Test("discriminated union narrowing and destructuring with defaults", () => {
|
||||
AssertEqual(EvaluateCommand({ kind: "move", x: 3, y: 4 }), 7);
|
||||
AssertEqual(EvaluateCommand({ kind: "damage", amount: 25, crit: true }), 50);
|
||||
AssertEqual(EvaluateCommand({ kind: "damage", amount: 25, crit: false }), 25);
|
||||
AssertEqual(EvaluateCommand({ kind: "noop" }), 0);
|
||||
|
||||
const cfg: { host: string; port?: number } = { host: "127.0.0.1" };
|
||||
const { host, port = 7777 } = cfg;
|
||||
AssertEqual(host, "127.0.0.1");
|
||||
AssertEqual(port, 7777);
|
||||
|
||||
const coords: [number, number, number] = [10, 20, 30];
|
||||
const [x, , z] = coords;
|
||||
AssertEqual(x, 10);
|
||||
AssertEqual(z, 30);
|
||||
|
||||
// 数值精度
|
||||
AssertNear(0.1 + 0.2, 0.3, 1e-6);
|
||||
});
|
||||
|
||||
Test("rest parameters and spread into function calls", () => {
|
||||
const SumAll = (...nums: number[]): number => {
|
||||
let total = 0;
|
||||
for (let idx = 0; idx < nums.length; idx++) {
|
||||
total += nums[idx];
|
||||
}
|
||||
return total;
|
||||
};
|
||||
const data = [2, 4, 6, 8];
|
||||
AssertEqual(SumAll(...data), 20);
|
||||
AssertEqual(SumAll(1, ...data, 9), 30);
|
||||
|
||||
const combined = [0, ...data, 10];
|
||||
AssertArrayEqual(combined, [0, 2, 4, 6, 8, 10]);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/** @noSelfInFile */
|
||||
|
||||
import {
|
||||
Suite,
|
||||
Test,
|
||||
AssertEqual,
|
||||
AssertTrue,
|
||||
AssertFalse,
|
||||
AssertNil,
|
||||
AssertArrayEqual,
|
||||
} from "../Harness/TestRunner";
|
||||
|
||||
function DivideWithRemainder(a: number, b: number): LuaMultiReturn<[boolean, number, number]> {
|
||||
if (b === 0) {
|
||||
return $multi(false, 0, 0);
|
||||
}
|
||||
const q = math.floor(a / b);
|
||||
const r = a % b;
|
||||
return $multi(true, q, r);
|
||||
}
|
||||
|
||||
// 函数重载
|
||||
function FormatId(id: number): string;
|
||||
function FormatId(prefix: string, id: number): string;
|
||||
function FormatId(a: number | string, b?: number): string {
|
||||
if (type(a) === "number") {
|
||||
return string.format("ID_%04d", a as number);
|
||||
}
|
||||
return string.format("%s_%04d", a as string, b ?? 0);
|
||||
}
|
||||
|
||||
interface CounterObj {
|
||||
value: number;
|
||||
Add(this: CounterObj, delta: number): number;
|
||||
}
|
||||
|
||||
export function RunFunctionsClosuresAndTuplesTests(): void {
|
||||
Suite("Syntax.FunctionsClosuresAndTuples", () => {
|
||||
Test("LuaMultiReturn and $multi destructuring", () => {
|
||||
const [ok1, q1, r1] = DivideWithRemainder(17, 5);
|
||||
AssertTrue(ok1);
|
||||
AssertEqual(q1, 3);
|
||||
AssertEqual(r1, 2);
|
||||
|
||||
const [ok2, q2, r2] = DivideWithRemainder(10, 0);
|
||||
AssertFalse(ok2);
|
||||
AssertEqual(q2, 0);
|
||||
AssertEqual(r2, 0);
|
||||
});
|
||||
|
||||
Test("function overloads, closures and upvalues", () => {
|
||||
AssertEqual(FormatId(7), "ID_0007");
|
||||
AssertEqual(FormatId("NPC", 42), "NPC_0042");
|
||||
|
||||
const MakeAccumulator = (start: number): ((this: void, delta: number) => number) => {
|
||||
let acc = start;
|
||||
return (delta: number) => {
|
||||
acc += delta;
|
||||
return acc;
|
||||
};
|
||||
};
|
||||
const acc = MakeAccumulator(10);
|
||||
AssertEqual(acc(5), 15);
|
||||
AssertEqual(acc(-3), 12);
|
||||
AssertEqual(acc(8), 20);
|
||||
});
|
||||
|
||||
Test("explicit self colon-call vs @noSelf dot-call", () => {
|
||||
const counter: CounterObj = {
|
||||
value: 10,
|
||||
Add(this: CounterObj, delta: number): number {
|
||||
this.value += delta;
|
||||
return this.value;
|
||||
},
|
||||
};
|
||||
AssertEqual(counter.Add(5), 15);
|
||||
AssertEqual(counter.Add(7), 22);
|
||||
});
|
||||
|
||||
Test("TS arrays (0-based -> Lua 1-based) and table operations", () => {
|
||||
const arr: number[] = [10, 20, 30, 40];
|
||||
AssertEqual(arr.length, 4);
|
||||
AssertEqual(arr[0], 10);
|
||||
AssertEqual(arr[3], 40);
|
||||
|
||||
arr.push(50);
|
||||
AssertEqual(arr.length, 5);
|
||||
AssertEqual(arr.pop(), 50);
|
||||
|
||||
// splice 删除中间元素不产生稀疏洞
|
||||
const removed = arr.splice(1, 2);
|
||||
AssertArrayEqual(removed, [20, 30]);
|
||||
AssertArrayEqual(arr, [10, 40]);
|
||||
|
||||
// table.insert / table.remove (注意 1-based)
|
||||
table.insert(arr, 2, 25);
|
||||
AssertArrayEqual(arr, [10, 25, 40]);
|
||||
table.remove(arr, 1);
|
||||
AssertArrayEqual(arr, [25, 40]);
|
||||
|
||||
// 排序与 join
|
||||
const unsorted = [5, 1, 4, 2, 3];
|
||||
unsorted.sort((a, b) => a - b);
|
||||
AssertArrayEqual(unsorted, [1, 2, 3, 4, 5]);
|
||||
AssertEqual(unsorted.join("-"), "1-2-3-4-5");
|
||||
AssertEqual(unsorted.indexOf(4), 3);
|
||||
AssertEqual(unsorted.indexOf(99), -1);
|
||||
});
|
||||
|
||||
Test("Record<K, V>, LuaTable and pairs() iteration", () => {
|
||||
const scores: Record<string, number | undefined> = {
|
||||
Alice: 100,
|
||||
Bob: 85,
|
||||
Carol: 92,
|
||||
};
|
||||
scores["Bob"] = undefined; // Lua 表删除键
|
||||
|
||||
let count = 0;
|
||||
let total = 0;
|
||||
for (const [k, v] of pairs(scores)) {
|
||||
if (v !== undefined) {
|
||||
count++;
|
||||
total += v;
|
||||
}
|
||||
AssertTrue(k !== "Bob");
|
||||
}
|
||||
AssertEqual(count, 2);
|
||||
AssertEqual(total, 192);
|
||||
|
||||
const luaTbl = new LuaTable<number, string>();
|
||||
luaTbl.set(101, "Sword");
|
||||
luaTbl.set(202, "Shield");
|
||||
AssertEqual(luaTbl.get(101), "Sword");
|
||||
AssertEqual(luaTbl.get(202), "Shield");
|
||||
luaTbl.set(101, undefined as unknown as string);
|
||||
AssertNil(luaTbl.get(101));
|
||||
});
|
||||
|
||||
Test("Lua patterns (replacing forbidden JS RegExp)", () => {
|
||||
const [tag, numStr] = string.match("Item_Sword_042", "^(%a+)_%a+_(%d+)$");
|
||||
AssertEqual(tag, "Item");
|
||||
AssertEqual(numStr, "042");
|
||||
|
||||
const [replaced, subCount] = string.gsub("HP: 100, MP: 50", "%d+", "999");
|
||||
AssertEqual(replaced, "HP: 999, MP: 999");
|
||||
AssertEqual(subCount, 2);
|
||||
|
||||
const tokens: string[] = [];
|
||||
for (const [tok] of string.gmatch("alpha,beta,gamma", "[^,]+")) {
|
||||
tokens[tokens.length] = tok;
|
||||
}
|
||||
AssertArrayEqual(tokens, ["alpha", "beta", "gamma"]);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import {
|
||||
Suite,
|
||||
Test,
|
||||
AssertEqual,
|
||||
AssertTrue,
|
||||
AssertFalse,
|
||||
AssertNil,
|
||||
} from "../Harness/TestRunner";
|
||||
|
||||
interface Identifiable {
|
||||
GetId(): number;
|
||||
}
|
||||
|
||||
abstract class BaseEntity implements Identifiable {
|
||||
protected id: number;
|
||||
protected name: string;
|
||||
|
||||
constructor(id: number, name: string) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
GetId(): number {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
GetName(): string {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
abstract Describe(): string;
|
||||
}
|
||||
|
||||
class PureMonster extends BaseEntity {
|
||||
static DefaultLevel = 1;
|
||||
private level: number;
|
||||
|
||||
constructor(id: number, name: string, level = PureMonster.DefaultLevel) {
|
||||
super(id, name);
|
||||
this.level = level;
|
||||
}
|
||||
|
||||
GetLevel(): number {
|
||||
return this.level;
|
||||
}
|
||||
|
||||
override Describe(): string {
|
||||
return `${this.name}#${this.id}(Lv.${this.level})`;
|
||||
}
|
||||
|
||||
static CompareLevel(this: void, a: PureMonster, b: PureMonster): number {
|
||||
return a.GetLevel() - b.GetLevel();
|
||||
}
|
||||
}
|
||||
|
||||
class RingBuffer<T> {
|
||||
private buffer: (T | undefined)[] = [];
|
||||
private head = 0;
|
||||
private count = 0;
|
||||
private capacity: number;
|
||||
|
||||
constructor(capacity: number) {
|
||||
this.capacity = capacity;
|
||||
}
|
||||
|
||||
Push(item: T): void {
|
||||
if (this.count < this.capacity) {
|
||||
const idx = (this.head + this.count) % this.capacity;
|
||||
this.buffer[idx] = item;
|
||||
this.count++;
|
||||
} else {
|
||||
this.buffer[this.head] = item;
|
||||
this.head = (this.head + 1) % this.capacity;
|
||||
}
|
||||
}
|
||||
|
||||
Pop(): T | undefined {
|
||||
if (this.count === 0) return undefined;
|
||||
const item = this.buffer[this.head];
|
||||
this.buffer[this.head] = undefined;
|
||||
this.head = (this.head + 1) % this.capacity;
|
||||
this.count--;
|
||||
return item;
|
||||
}
|
||||
|
||||
GetCount(): number {
|
||||
return this.count;
|
||||
}
|
||||
}
|
||||
|
||||
function FindById<T extends Identifiable>(this: void, list: T[], targetId: number): T | undefined {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
if (list[i].GetId() === targetId) {
|
||||
return list[i];
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function SafeFrameworkBoundary(this: void, shouldThrow: boolean): LuaMultiReturn<[boolean, string]> {
|
||||
/** @unlua-allow-try */
|
||||
try {
|
||||
if (shouldThrow) {
|
||||
/** @unlua-allow-try */
|
||||
throw "simulated_boundary_error";
|
||||
}
|
||||
return $multi(true, "ok");
|
||||
} catch (e) {
|
||||
return $multi(false, tostring(e));
|
||||
}
|
||||
}
|
||||
|
||||
export function RunPureClassesAndGenericsTests(this: void): void {
|
||||
Suite("Syntax.PureClassesAndGenerics", () => {
|
||||
Test("pure TS class inheritance, abstract methods and static helpers", () => {
|
||||
const m1 = new PureMonster(1, "Slime");
|
||||
const m2 = new PureMonster(2, "Dragon", 50);
|
||||
|
||||
AssertEqual(m1.GetId(), 1);
|
||||
AssertEqual(m1.GetLevel(), 1);
|
||||
AssertEqual(m1.Describe(), "Slime#1(Lv.1)");
|
||||
AssertEqual(m2.Describe(), "Dragon#2(Lv.50)");
|
||||
AssertTrue(PureMonster.CompareLevel(m2, m1) > 0);
|
||||
AssertTrue(m1 instanceof PureMonster);
|
||||
AssertTrue(m1 instanceof BaseEntity);
|
||||
});
|
||||
|
||||
Test("generic class RingBuffer<T> and constrained generic function", () => {
|
||||
const rb = new RingBuffer<number>(3);
|
||||
rb.Push(10);
|
||||
rb.Push(20);
|
||||
rb.Push(30);
|
||||
rb.Push(40); // overwrites 10
|
||||
AssertEqual(rb.GetCount(), 3);
|
||||
AssertEqual(rb.Pop(), 20);
|
||||
AssertEqual(rb.Pop(), 30);
|
||||
AssertEqual(rb.Pop(), 40);
|
||||
AssertNil(rb.Pop());
|
||||
|
||||
const monsters = [new PureMonster(10, "Orc", 5), new PureMonster(20, "Goblin", 2)];
|
||||
const found = FindById(monsters, 20);
|
||||
AssertTrue(found !== undefined);
|
||||
AssertEqual(found!.GetName(), "Goblin");
|
||||
AssertNil(FindById(monsters, 999));
|
||||
});
|
||||
|
||||
Test("@unlua-allow-try framework boundary try/catch/throw", () => {
|
||||
const [ok1, msg1] = SafeFrameworkBoundary(false);
|
||||
AssertTrue(ok1);
|
||||
AssertEqual(msg1, "ok");
|
||||
|
||||
const [ok2, msg2] = SafeFrameworkBoundary(true);
|
||||
AssertFalse(ok2);
|
||||
AssertTrue(string.find(msg2, "simulated_boundary_error", 1, true)[0] !== undefined);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
export interface BaseActorConfig {
|
||||
name: string;
|
||||
hp?: number;
|
||||
}
|
||||
|
||||
export type ActorFaction = "Ally" | "Enemy" | "Neutral";
|
||||
|
||||
@unlua
|
||||
export default class UnLuaBaseActor extends UE.AActor {
|
||||
static readonly DEFAULT_HP = 100;
|
||||
|
||||
protected hp!: number;
|
||||
protected callTrace!: string[];
|
||||
|
||||
ReceiveBeginPlay(): void {
|
||||
super.ReceiveBeginPlay();
|
||||
this.hp = UnLuaBaseActor.DEFAULT_HP;
|
||||
this.callTrace = ["Base.ReceiveBeginPlay"];
|
||||
}
|
||||
|
||||
ApplyConfig({ name, hp = UnLuaBaseActor.DEFAULT_HP }: BaseActorConfig): string {
|
||||
this.hp = hp;
|
||||
return `${name}:${this.hp}`;
|
||||
}
|
||||
|
||||
SumScores([first, second = 5, ...rest]: number[]): number {
|
||||
let sum = first + second;
|
||||
for (let i = 0; i < rest.length; i++) {
|
||||
sum += rest[i];
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
GetTrace(): string[] {
|
||||
return this.callTrace;
|
||||
}
|
||||
|
||||
GetHp(): number {
|
||||
return this.hp;
|
||||
}
|
||||
|
||||
ComputeBonus(baseVal: number, multiplier = 2): number {
|
||||
return baseVal * multiplier;
|
||||
}
|
||||
|
||||
static StaticWithSelf(delta: number): number {
|
||||
return this.DEFAULT_HP + delta;
|
||||
}
|
||||
|
||||
static StaticNoSelf(this: void, a: number, b: number): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
/** @noSelf */
|
||||
static StaticDocNoSelf(x: number): number {
|
||||
return x * 3;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
export interface ExplicitWidgetModel {
|
||||
title: string;
|
||||
}
|
||||
|
||||
@unlua("Tests.Syntax.UnLuaBaseActor")
|
||||
export default class UnLuaExplicitWidget {
|
||||
private title!: string;
|
||||
|
||||
Construct(model: ExplicitWidgetModel): void {
|
||||
this.title = model.title;
|
||||
}
|
||||
|
||||
GetTitle(): string {
|
||||
return this.title;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import UnLuaSubActor from "./UnLuaSubActor";
|
||||
|
||||
@unlua
|
||||
export default class UnLuaGrandChildActor extends UnLuaSubActor {
|
||||
private tier!: number;
|
||||
|
||||
ReceiveBeginPlay(): void {
|
||||
super.ReceiveBeginPlay();
|
||||
this.tier = 3;
|
||||
this.callTrace[this.callTrace.length] = "GrandChild.ReceiveBeginPlay";
|
||||
}
|
||||
|
||||
override ComputeBonus(baseVal: number, multiplier = 2): number {
|
||||
return super.ComputeBonus(baseVal, multiplier) + this.tier;
|
||||
}
|
||||
|
||||
GetTier(): number {
|
||||
return this.tier;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import UnLuaBaseActor, { BaseActorConfig, type ActorFaction } from "./UnLuaBaseActor";
|
||||
|
||||
@unlua
|
||||
export default class UnLuaSubActor extends UnLuaBaseActor {
|
||||
protected faction!: ActorFaction;
|
||||
|
||||
ReceiveBeginPlay(): void {
|
||||
super.ReceiveBeginPlay();
|
||||
this.faction = "Ally";
|
||||
this.callTrace[this.callTrace.length] = "Sub.ReceiveBeginPlay";
|
||||
}
|
||||
|
||||
override ComputeBonus(baseVal: number, multiplier = 2): number {
|
||||
return super.ComputeBonus(baseVal, multiplier) + 10;
|
||||
}
|
||||
|
||||
SetupWithFaction(cfg: BaseActorConfig, faction: ActorFaction): string {
|
||||
this.faction = faction;
|
||||
return `${super.ApplyConfig(cfg)}[${this.faction}]`;
|
||||
}
|
||||
|
||||
GetFaction(): ActorFaction {
|
||||
return this.faction;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/** @noSelfInFile */
|
||||
|
||||
import {
|
||||
Suite,
|
||||
Test,
|
||||
AssertEqual,
|
||||
AssertTrue,
|
||||
AssertArrayEqual,
|
||||
} from "../Harness/TestRunner";
|
||||
import { CreateBoundInstance, GetMockState, ResetMockState } from "../Harness/MockUnLuaRuntime";
|
||||
import UnLuaBaseActor from "./UnLuaBaseActor";
|
||||
import UnLuaSubActor from "./UnLuaSubActor";
|
||||
import UnLuaGrandChildActor from "./UnLuaGrandChildActor";
|
||||
import UnLuaExplicitWidget from "./UnLuaExplicitWidget";
|
||||
|
||||
export function RunUnLuaSyntaxTests(): void {
|
||||
Suite("Syntax.UnLuaClassFeatures", () => {
|
||||
Test("@unlua base class: UnLua.Class(), self.Overridden, static methods and destructured params", () => {
|
||||
ResetMockState();
|
||||
const actor = CreateBoundInstance<UnLuaBaseActor>(
|
||||
UnLuaBaseActor as unknown as Record<string, any>,
|
||||
"AActor"
|
||||
);
|
||||
actor.ReceiveBeginPlay();
|
||||
|
||||
AssertEqual(actor.GetHp(), 100);
|
||||
AssertArrayEqual(actor.GetTrace(), ["Base.ReceiveBeginPlay"]);
|
||||
AssertArrayEqual(GetMockState().overriddenCalls, ["AActor.ReceiveBeginPlay"]);
|
||||
|
||||
// 解构对象与数组参数(含默认值与 rest)
|
||||
AssertEqual(actor.ApplyConfig({ name: "Hero" }), "Hero:100");
|
||||
AssertEqual(actor.ApplyConfig({ name: "Boss", hp: 500 }), "Boss:500");
|
||||
AssertEqual(actor.SumScores([10]), 15);
|
||||
AssertEqual(actor.SumScores([1, 2, 3, 4]), 10);
|
||||
|
||||
// 静态方法(含 self 冒号调用与 @noSelf/this:void 点号调用)
|
||||
AssertEqual(UnLuaBaseActor.StaticWithSelf(25), 125);
|
||||
AssertEqual(UnLuaBaseActor.StaticNoSelf(7, 8), 15);
|
||||
AssertEqual(UnLuaBaseActor.StaticDocNoSelf(9), 27);
|
||||
|
||||
// UObject IsA 与 IsValid
|
||||
AssertTrue(actor.IsA(UE.AActor.StaticClass()));
|
||||
AssertTrue(UE.UKismetSystemLibrary.IsValid(actor));
|
||||
});
|
||||
|
||||
Test("@unlua 3-level inheritance (GrandChild -> Sub -> Base) avoids self.Super infinite recursion", () => {
|
||||
ResetMockState();
|
||||
const grand = CreateBoundInstance<UnLuaGrandChildActor>(
|
||||
UnLuaGrandChildActor as unknown as Record<string, any>,
|
||||
"AActor"
|
||||
);
|
||||
grand.ReceiveBeginPlay();
|
||||
|
||||
AssertArrayEqual(grand.GetTrace(), [
|
||||
"Base.ReceiveBeginPlay",
|
||||
"Sub.ReceiveBeginPlay",
|
||||
"GrandChild.ReceiveBeginPlay",
|
||||
]);
|
||||
AssertArrayEqual(GetMockState().overriddenCalls, ["AActor.ReceiveBeginPlay"]);
|
||||
AssertEqual(grand.GetFaction(), "Ally");
|
||||
AssertEqual(grand.GetTier(), 3);
|
||||
|
||||
// Base: 10*2 = 20, Sub: +10 = 30, GrandChild: +3 = 33
|
||||
AssertEqual(grand.ComputeBonus(10), 33);
|
||||
AssertEqual(grand.ComputeBonus(10, 4), 53);
|
||||
|
||||
// 混合默认+纯类型导入的父类方法调用
|
||||
const summary = grand.SetupWithFaction({ name: "Knight", hp: 250 }, "Enemy");
|
||||
AssertEqual(summary, "Knight:250[Enemy]");
|
||||
AssertEqual(grand.GetFaction(), "Enemy");
|
||||
});
|
||||
|
||||
Test("@unlua explicit base path class without extends", () => {
|
||||
const widgetCls = UnLuaExplicitWidget as unknown as Record<string, any>;
|
||||
AssertEqual(widgetCls.Super, UnLuaBaseActor);
|
||||
|
||||
const widget = CreateBoundInstance<UnLuaExplicitWidget>(widgetCls, "UUserWidget");
|
||||
widget.Construct({ title: "MainHUD" });
|
||||
AssertEqual(widget.GetTitle(), "MainHUD");
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* 参考 UnLua 官方示例 01_HelloWorld:
|
||||
* 演示最简 @unlua Actor 绑定、ReceiveBeginPlay、屏幕打印与 UnLua.Log。
|
||||
*/
|
||||
@unlua
|
||||
export default class Ex01_HelloWorld extends UE.AActor {
|
||||
private greeting!: string;
|
||||
|
||||
ReceiveBeginPlay(): void {
|
||||
this.greeting = `Hello UnLua from TypeScript (${_VERSION})!`;
|
||||
UnLua.Log(this.greeting);
|
||||
UE.UKismetSystemLibrary.PrintString(
|
||||
this,
|
||||
this.greeting,
|
||||
true,
|
||||
true,
|
||||
UE.FLinearColor(0.1, 0.9, 0.4, 1.0),
|
||||
5.0
|
||||
);
|
||||
}
|
||||
|
||||
GetGreeting(): string {
|
||||
return this.greeting;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* 参考 UnLua 官方示例 02_OverrideBlueprintEvents:
|
||||
* 演示覆写蓝图/Actor 生命周期事件,并通过 super.Method() 调用 self.Overridden.Method(self, ...)。
|
||||
*/
|
||||
@unlua
|
||||
export default class Ex02_OverrideBlueprintEvents extends UE.AActor {
|
||||
private events!: string[];
|
||||
private totalDamage!: number;
|
||||
private elapsed!: number;
|
||||
private overlapCount!: number;
|
||||
|
||||
Initialize(_Initializer?: unknown): void {
|
||||
this.events = ["Initialize"];
|
||||
this.totalDamage = 0;
|
||||
this.elapsed = 0;
|
||||
this.overlapCount = 0;
|
||||
}
|
||||
|
||||
UserConstructionScript(): void {
|
||||
super.UserConstructionScript();
|
||||
this.events[this.events.length] = "UserConstructionScript";
|
||||
}
|
||||
|
||||
ReceiveBeginPlay(): void {
|
||||
super.ReceiveBeginPlay();
|
||||
this.events[this.events.length] = "ReceiveBeginPlay";
|
||||
}
|
||||
|
||||
ReceiveTick(DeltaSeconds: number): void {
|
||||
super.ReceiveTick(DeltaSeconds);
|
||||
this.elapsed += DeltaSeconds;
|
||||
}
|
||||
|
||||
ReceiveAnyDamage(
|
||||
Damage: number,
|
||||
_DamageType: UE.UDamageType | undefined,
|
||||
_InstigatedBy: UE.AController | undefined,
|
||||
_DamageCauser: UE.AActor | undefined
|
||||
): void {
|
||||
super.ReceiveAnyDamage(Damage, _DamageType, _InstigatedBy, _DamageCauser);
|
||||
this.totalDamage += Damage;
|
||||
this.events[this.events.length] = `Damage:${Damage}`;
|
||||
}
|
||||
|
||||
ReceiveActorBeginOverlap(OtherActor: UE.AActor | undefined): void {
|
||||
super.ReceiveActorBeginOverlap(OtherActor);
|
||||
if (UE.UKismetSystemLibrary.IsValid(OtherActor)) {
|
||||
this.overlapCount++;
|
||||
this.events[this.events.length] = `Overlap:${OtherActor!.GetName()}`;
|
||||
}
|
||||
}
|
||||
|
||||
ReceiveEndPlay(EndPlayReason: UE.EEndPlayReason): void {
|
||||
super.ReceiveEndPlay(EndPlayReason);
|
||||
this.events[this.events.length] = `EndPlay:${EndPlayReason}`;
|
||||
}
|
||||
|
||||
GetEvents(): string[] {
|
||||
return this.events;
|
||||
}
|
||||
|
||||
GetTotalDamage(): number {
|
||||
return this.totalDamage;
|
||||
}
|
||||
|
||||
GetElapsed(): number {
|
||||
return this.elapsed;
|
||||
}
|
||||
|
||||
GetOverlapCount(): number {
|
||||
return this.overlapCount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* 参考 UnLua 官方示例 03_BindDelegates:
|
||||
* 演示 MulticastDelegate (Add/Remove/Clear)、单播 FScriptDelegate (Bind/Unbind/Execute)
|
||||
* 以及 K2_SetTimerDelegate + UnLua.Delegate(this, this.OnTimer) 定时器委托绑定与销毁清理。
|
||||
*/
|
||||
@unlua
|
||||
export default class Ex03_BindDelegates extends UE.UUserWidget {
|
||||
ClickMeButton!: UE.UButton;
|
||||
CustomSingleDelegate!: UE.FScriptDelegate<(value: number) => number>;
|
||||
|
||||
private clickCount!: number;
|
||||
private timerTickCount!: number;
|
||||
private timerHandle!: UE.FTimerHandle;
|
||||
|
||||
Construct(): void {
|
||||
this.clickCount = 0;
|
||||
this.timerTickCount = 0;
|
||||
|
||||
if (this.ClickMeButton !== undefined) {
|
||||
this.ClickMeButton.OnClicked.Add(this, this.OnButtonClicked);
|
||||
}
|
||||
|
||||
if (this.CustomSingleDelegate !== undefined) {
|
||||
this.CustomSingleDelegate.Bind(this, this.OnCustomExecute);
|
||||
}
|
||||
|
||||
// UnLua.Delegate 编译期宏直接内联为 { self, self.OnTimerTick }
|
||||
this.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate(
|
||||
UnLua.Delegate(this, this.OnTimerTick),
|
||||
0.5,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
OnButtonClicked(): void {
|
||||
this.clickCount++;
|
||||
}
|
||||
|
||||
OnCustomExecute(value: number): number {
|
||||
return value * 10 + this.clickCount;
|
||||
}
|
||||
|
||||
OnTimerTick(): void {
|
||||
if (!UE.UKismetSystemLibrary.IsValid(this)) {
|
||||
return;
|
||||
}
|
||||
this.timerTickCount++;
|
||||
}
|
||||
|
||||
Destruct(): void {
|
||||
if (this.ClickMeButton !== undefined) {
|
||||
this.ClickMeButton.OnClicked.Remove(this, this.OnButtonClicked);
|
||||
}
|
||||
if (this.CustomSingleDelegate !== undefined) {
|
||||
this.CustomSingleDelegate.Unbind();
|
||||
}
|
||||
UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(this, this.timerHandle);
|
||||
}
|
||||
|
||||
GetClickCount(): number {
|
||||
return this.clickCount;
|
||||
}
|
||||
|
||||
GetTimerTickCount(): number {
|
||||
return this.timerTickCount;
|
||||
}
|
||||
|
||||
GetTimerHandle(): UE.FTimerHandle {
|
||||
return this.timerHandle;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import type Ex04_DynamicSpawnedActor from "./Ex04_DynamicSpawnedActor";
|
||||
import type Ex04_DynamicObject from "./Ex04_DynamicObject";
|
||||
|
||||
/**
|
||||
* 参考 UnLua 官方示例 04_DynamicBinding:
|
||||
* 演示 World:SpawnActor、World:SpawnActorEx 与 UE.NewObject 动态绑定 Lua 模块并传入 Initializer 表。
|
||||
*/
|
||||
@unlua
|
||||
export default class Ex04_DynamicBinding extends UE.AActor {
|
||||
SpawnDynamicActor(tag: string, power: number): Ex04_DynamicSpawnedActor | undefined {
|
||||
const world = this.GetWorld();
|
||||
const actorClass = UE.UClass.Load("/Game/Blueprints/BP_DynamicDemo.BP_DynamicDemo_C");
|
||||
if (!world || !actorClass) {
|
||||
return undefined;
|
||||
}
|
||||
const transform = UE.FTransform(
|
||||
UE.FRotator(0, 90, 0).ToQuat(),
|
||||
UE.FVector(100, 200, 300),
|
||||
UE.FVector(1, 1, 1)
|
||||
);
|
||||
return world.SpawnActor<Ex04_DynamicSpawnedActor>(
|
||||
actorClass,
|
||||
transform,
|
||||
UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn,
|
||||
this,
|
||||
undefined,
|
||||
"Tests.UnLuaExamples.Ex04_DynamicSpawnedActor",
|
||||
{ InitTag: tag, InitPower: power }
|
||||
);
|
||||
}
|
||||
|
||||
SpawnDynamicActorEx(tag: string): Ex04_DynamicSpawnedActor | undefined {
|
||||
const world = this.GetWorld();
|
||||
const actorClass = UE.LoadClass("/Game/Blueprints/BP_DynamicDemoEx.BP_DynamicDemoEx_C");
|
||||
if (!world || !actorClass) {
|
||||
return undefined;
|
||||
}
|
||||
const params = UE.FActorSpawnParameters();
|
||||
params.Name = "ExSpawnedActor";
|
||||
params.bNoFail = true;
|
||||
params.Owner = this;
|
||||
params.SpawnCollisionHandlingOverride = UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn;
|
||||
|
||||
return world.SpawnActorEx<Ex04_DynamicSpawnedActor>(
|
||||
actorClass,
|
||||
UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(10, 20, 30), UE.FVector(1, 1, 1)),
|
||||
{ InitTag: tag, InitPower: 77 },
|
||||
"Tests.UnLuaExamples.Ex04_DynamicSpawnedActor",
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
CreateDynamicObject(seed: number): Ex04_DynamicObject | undefined {
|
||||
const objClass = UE.UClass.Load("/Script/CoreUObject.Object");
|
||||
if (!objClass) {
|
||||
return undefined;
|
||||
}
|
||||
return UE.NewObject<Ex04_DynamicObject>(
|
||||
objClass,
|
||||
this,
|
||||
"DynamicObjectInstance",
|
||||
"Tests.UnLuaExamples.Ex04_DynamicObject",
|
||||
{ Seed: seed }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
export interface DynamicObjectInitializer {
|
||||
Seed?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 参考 UnLua 官方示例 04_DynamicBinding:通过 UE.NewObject 动态创建的 UObject。
|
||||
*/
|
||||
@unlua
|
||||
export default class Ex04_DynamicObject extends UE.UObject {
|
||||
private seed!: number;
|
||||
|
||||
Initialize(Initializer?: DynamicObjectInitializer): void {
|
||||
this.seed = Initializer?.Seed ?? 1;
|
||||
}
|
||||
|
||||
NextValue(): number {
|
||||
this.seed = this.seed * 2 + 1;
|
||||
return this.seed;
|
||||
}
|
||||
|
||||
GetSeed(): number {
|
||||
return this.seed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
export interface DynamicActorInitializer {
|
||||
InitTag?: string;
|
||||
InitPower?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 参考 UnLua 官方示例 04_DynamicBinding:被动态 Spawn 并绑定 Lua 脚本的 Actor。
|
||||
*/
|
||||
@unlua
|
||||
export default class Ex04_DynamicSpawnedActor extends UE.AActor {
|
||||
private initTag!: string;
|
||||
private initPower!: number;
|
||||
private beginPlayCalled!: boolean;
|
||||
|
||||
Initialize(Initializer?: DynamicActorInitializer): void {
|
||||
this.initTag = Initializer?.InitTag ?? "Default";
|
||||
this.initPower = Initializer?.InitPower ?? 0;
|
||||
this.beginPlayCalled = false;
|
||||
}
|
||||
|
||||
ReceiveBeginPlay(): void {
|
||||
super.ReceiveBeginPlay();
|
||||
this.beginPlayCalled = true;
|
||||
}
|
||||
|
||||
GetInitTag(): string {
|
||||
return this.initTag;
|
||||
}
|
||||
|
||||
GetInitPower(): number {
|
||||
return this.initPower;
|
||||
}
|
||||
|
||||
IsBeginPlayCalled(): boolean {
|
||||
return this.beginPlayCalled;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* 参考 UnLua 官方示例 05_BindInputs:
|
||||
* 演示 UnLua.Input.BindKey / BindAction / BindAxis 以及 UnLua.EnhancedInput.BindAction。
|
||||
*/
|
||||
@unlua
|
||||
export default class Ex05_BindInputs extends UE.APlayerController {
|
||||
private lastAction!: string;
|
||||
private moveForwardValue!: number;
|
||||
private enhancedCount!: number;
|
||||
|
||||
ReceiveBeginPlay(): void {
|
||||
super.ReceiveBeginPlay();
|
||||
this.lastAction = "";
|
||||
this.moveForwardValue = 0;
|
||||
this.enhancedCount = 0;
|
||||
}
|
||||
|
||||
HandleSpacePressed(): void {
|
||||
this.lastAction = "SpaceBar:Pressed";
|
||||
}
|
||||
|
||||
HandleCtrlSave(): void {
|
||||
this.lastAction = "Ctrl+S";
|
||||
}
|
||||
|
||||
HandleJumpAction(): void {
|
||||
this.lastAction = "Action:Jump";
|
||||
}
|
||||
|
||||
HandleMoveForward(axisValue: number): void {
|
||||
this.moveForwardValue = axisValue;
|
||||
}
|
||||
|
||||
HandleEnhancedMove(actionValue: number): void {
|
||||
this.enhancedCount++;
|
||||
this.moveForwardValue = actionValue;
|
||||
}
|
||||
|
||||
GetLastAction(): string {
|
||||
return this.lastAction;
|
||||
}
|
||||
|
||||
GetMoveForwardValue(): number {
|
||||
return this.moveForwardValue;
|
||||
}
|
||||
|
||||
GetEnhancedCount(): number {
|
||||
return this.enhancedCount;
|
||||
}
|
||||
}
|
||||
|
||||
UnLua.Input.BindKey(Ex05_BindInputs, "SpaceBar", "Pressed", function (this: Ex05_BindInputs) {
|
||||
this.HandleSpacePressed();
|
||||
});
|
||||
|
||||
UnLua.Input.BindKey(
|
||||
Ex05_BindInputs,
|
||||
"S",
|
||||
"Pressed",
|
||||
function (this: Ex05_BindInputs) {
|
||||
this.HandleCtrlSave();
|
||||
},
|
||||
{ Ctrl: true }
|
||||
);
|
||||
|
||||
UnLua.Input.BindAction(Ex05_BindInputs, "Jump", "Pressed", function (this: Ex05_BindInputs) {
|
||||
this.HandleJumpAction();
|
||||
});
|
||||
|
||||
UnLua.Input.BindAxis(
|
||||
Ex05_BindInputs,
|
||||
"MoveForward",
|
||||
function (this: Ex05_BindInputs, axisValue: number) {
|
||||
this.HandleMoveForward(axisValue);
|
||||
}
|
||||
);
|
||||
|
||||
UnLua.EnhancedInput.BindAction(
|
||||
Ex05_BindInputs,
|
||||
"/Game/Input/IA_Move.IA_Move",
|
||||
"Triggered",
|
||||
function (this: Ex05_BindInputs, actionValue: number) {
|
||||
this.HandleEnhancedMove(actionValue);
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,134 @@
|
||||
/** @noSelfInFile */
|
||||
|
||||
import {
|
||||
AssertEqual,
|
||||
AssertTrue,
|
||||
AssertFalse,
|
||||
AssertNil,
|
||||
AssertArrayEqual,
|
||||
} from "../Harness/TestRunner";
|
||||
|
||||
/**
|
||||
* 参考 UnLua 官方示例 06_NativeContainers:
|
||||
* 演示 UE.TArray / UE.TMap / UE.TSet 的构造(使用 UE.int32 / UE.FString Token)、
|
||||
* 1-based 索引访问、CRUD、ToTable 与原生 pairs() 遍历。
|
||||
*/
|
||||
export function VerifyTArrayOperations(): void {
|
||||
const arr = UE.TArray<number>(UE.int32);
|
||||
AssertTrue(arr.Reserve(8));
|
||||
AssertEqual(arr.Length(), 0);
|
||||
|
||||
AssertEqual(arr.Add(10), 1);
|
||||
AssertEqual(arr.Add(20), 2);
|
||||
AssertEqual(arr.Add(30), 3);
|
||||
AssertEqual(arr.Length(), 3);
|
||||
AssertEqual(arr.Num(), 3);
|
||||
|
||||
// 1-based Get / Set / LastIndex / IsValidIndex
|
||||
AssertEqual(arr.Get(1), 10);
|
||||
AssertEqual(arr.Get(3), 30);
|
||||
AssertEqual(arr.LastIndex(), 3);
|
||||
AssertTrue(arr.IsValidIndex(1));
|
||||
AssertFalse(arr.IsValidIndex(0));
|
||||
AssertFalse(arr.IsValidIndex(4));
|
||||
|
||||
arr.Set(2, 25);
|
||||
AssertEqual(arr.Get(2), 25);
|
||||
AssertEqual(arr.Find(25), 2);
|
||||
AssertTrue(arr.Contains(25));
|
||||
AssertFalse(arr.Contains(999));
|
||||
|
||||
// AddUnique
|
||||
AssertEqual(arr.AddUnique(25), 0);
|
||||
AssertEqual(arr.AddUnique(40), 4);
|
||||
AssertEqual(arr.Length(), 4);
|
||||
|
||||
// Insert & Swap & Remove & RemoveItem
|
||||
arr.Insert(15, 2); // [10, 15, 25, 30, 40]
|
||||
AssertEqual(arr.Get(2), 15);
|
||||
arr.Swap(1, 5); // [40, 15, 25, 30, 10]
|
||||
AssertEqual(arr.Get(1), 40);
|
||||
AssertEqual(arr.Get(5), 10);
|
||||
|
||||
arr.Add(15);
|
||||
const removedCount = arr.RemoveItem(15);
|
||||
AssertEqual(removedCount, 2);
|
||||
AssertFalse(arr.Contains(15));
|
||||
|
||||
// Append & ToTable
|
||||
const other = UE.TArray<number>(UE.int32);
|
||||
other.Add(100);
|
||||
other.Add(200);
|
||||
arr.Append(other);
|
||||
const tbl = arr.ToTable();
|
||||
AssertArrayEqual(tbl, [40, 25, 30, 10, 100, 200]);
|
||||
|
||||
// for..of 直接编译为 Lua 原生 pairs(arr) 遍历 TArray
|
||||
let sum = 0;
|
||||
for (const [idx, val] of arr) {
|
||||
AssertTrue(idx >= 1);
|
||||
sum += val;
|
||||
}
|
||||
AssertEqual(sum, 405);
|
||||
|
||||
arr.Clear();
|
||||
AssertEqual(arr.Length(), 0);
|
||||
}
|
||||
|
||||
export function VerifyTMapOperations(): void {
|
||||
const map = UE.TMap<string, number>(UE.FString, UE.int32);
|
||||
map.Add("HP", 100);
|
||||
map.Add("MP", 50);
|
||||
map.Add("ATK", 35);
|
||||
|
||||
AssertEqual(map.Length(), 3);
|
||||
AssertEqual(map.Find("HP"), 100);
|
||||
AssertEqual(map.FindRef("MP"), 50);
|
||||
AssertNil(map.Find("DEF"));
|
||||
|
||||
// 覆盖已有键
|
||||
map.Add("HP", 120);
|
||||
AssertEqual(map.Find("HP"), 120);
|
||||
|
||||
// Keys / Values / ToTable
|
||||
AssertEqual(map.Keys().Length(), 3);
|
||||
AssertEqual(map.Values().Length(), 3);
|
||||
const tbl = map.ToTable();
|
||||
AssertEqual(tbl["ATK"], 35);
|
||||
|
||||
// for..of 直接编译为 Lua 原生 pairs(map) 遍历 TMap
|
||||
let sum = 0;
|
||||
for (const [_k, v] of map) {
|
||||
sum += v;
|
||||
}
|
||||
AssertEqual(sum, 205);
|
||||
|
||||
AssertTrue(map.Remove("MP"));
|
||||
AssertFalse(map.Remove("NotExist"));
|
||||
AssertEqual(map.Length(), 2);
|
||||
|
||||
map.Clear();
|
||||
AssertEqual(map.Length(), 0);
|
||||
}
|
||||
|
||||
export function VerifyTSetOperations(): void {
|
||||
const set = UE.TSet<string>(UE.FString);
|
||||
set.Add("Fire");
|
||||
set.Add("Ice");
|
||||
set.Add("Fire"); // duplicate ignored
|
||||
|
||||
AssertEqual(set.Length(), 2);
|
||||
AssertTrue(set.Contains("Fire"));
|
||||
AssertFalse(set.Contains("Poison"));
|
||||
|
||||
const asArr = set.ToArray();
|
||||
AssertEqual(asArr.Length(), 2);
|
||||
AssertEqual(set.ToTable().length, 2);
|
||||
|
||||
AssertTrue(set.Remove("Ice"));
|
||||
AssertFalse(set.Remove("Ice"));
|
||||
AssertEqual(set.Length(), 1);
|
||||
|
||||
set.Clear();
|
||||
AssertEqual(set.Length(), 0);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* 参考 UnLua 官方示例 07_CallLatentFunction:
|
||||
* 演示用 Lua coroutine 驱动 UE Latent 函数(UKismetSystemLibrary.Delay),
|
||||
* 并在每次恢复后校验 IsValid(this) 防止对象已被销毁。
|
||||
*/
|
||||
@unlua
|
||||
export default class Ex07_CallLatentFunction extends UE.AActor {
|
||||
private steps!: string[];
|
||||
private completed!: boolean;
|
||||
|
||||
ReceiveBeginPlay(): void {
|
||||
super.ReceiveBeginPlay();
|
||||
this.steps = [];
|
||||
this.completed = false;
|
||||
|
||||
const co = coroutine.create((actor: Ex07_CallLatentFunction) => {
|
||||
actor.RunSequence();
|
||||
});
|
||||
const [ok, err] = coroutine.resume(co, this);
|
||||
if (!ok) {
|
||||
UnLua.LogError("Ex07 coroutine failed:", tostring(err));
|
||||
}
|
||||
}
|
||||
|
||||
private RunSequence(): void {
|
||||
this.steps[this.steps.length] = "Step1:Start";
|
||||
|
||||
UE.UKismetSystemLibrary.Delay(this, 0.5);
|
||||
if (!UE.UKismetSystemLibrary.IsValid(this)) {
|
||||
return;
|
||||
}
|
||||
this.steps[this.steps.length] = "Step2:After0.5s";
|
||||
|
||||
UE.UKismetSystemLibrary.Delay(this, 1.0);
|
||||
if (!UE.UKismetSystemLibrary.IsValid(this)) {
|
||||
return;
|
||||
}
|
||||
this.steps[this.steps.length] = "Step3:Done";
|
||||
this.completed = true;
|
||||
}
|
||||
|
||||
GetSteps(): string[] {
|
||||
return this.steps;
|
||||
}
|
||||
|
||||
IsCompleted(): boolean {
|
||||
return this.completed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* 参考 UnLua 官方示例 08/09(结构体数学运算、Out 参数多返回值、热路径缓存结构体):
|
||||
* 演示 FVector/FRotator/FTransform 运算、LineTraceSingle 多返回值与 K2_SetActorLocation。
|
||||
*/
|
||||
@unlua
|
||||
export default class Ex08_StructAndTrace extends UE.AActor {
|
||||
private _tmpStart!: UE.FVector;
|
||||
private _tmpEnd!: UE.FVector;
|
||||
private _tmpHit!: UE.FHitResult;
|
||||
private _ignoreActors!: UE.TArray<UE.AActor>;
|
||||
|
||||
ReceiveBeginPlay(): void {
|
||||
super.ReceiveBeginPlay();
|
||||
this._tmpStart = UE.FVector(0, 0, 0);
|
||||
this._tmpEnd = UE.FVector(0, 0, 0);
|
||||
this._tmpHit = UE.FHitResult();
|
||||
this._ignoreActors = UE.TArray<UE.AActor>(UE.AActor.StaticClass());
|
||||
this._ignoreActors.Add(this);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
TraceForward(distance: number): LuaMultiReturn<[boolean, number, UE.FVector]> {
|
||||
const origin = this.K2_GetActorLocation();
|
||||
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(
|
||||
this,
|
||||
this._tmpStart,
|
||||
this._tmpEnd,
|
||||
UE.ETraceTypeQuery.TraceTypeQuery1,
|
||||
false,
|
||||
this._ignoreActors,
|
||||
UE.EDrawDebugTrace.None,
|
||||
this._tmpHit,
|
||||
true
|
||||
);
|
||||
return $multi(bHit, hit.Distance, hit.ImpactPoint);
|
||||
}
|
||||
|
||||
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);
|
||||
return bMoved;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 参考 UnLua 官方示例 11_ReleaseUMG & 资源加载/手动 GC 引用管理:
|
||||
* 演示 UE.UObject.Load、UnLua.Ref / UnLua.Unref、FWeakObjectPtr 与 UUserWidget 完整生命周期。
|
||||
*/
|
||||
@unlua
|
||||
export default class Ex09_AssetRefAndUMG extends UE.UUserWidget {
|
||||
private loadedAsset!: UE.UObject | undefined;
|
||||
private refProxy!: unknown;
|
||||
private weakRef!: UE.FWeakObjectPtr;
|
||||
private isConstructed!: boolean;
|
||||
private isDestructed!: boolean;
|
||||
|
||||
Initialize(_Initializer?: unknown): void {
|
||||
this.isConstructed = false;
|
||||
this.isDestructed = false;
|
||||
this.weakRef = UE.FWeakObjectPtr();
|
||||
}
|
||||
|
||||
Construct(): void {
|
||||
this.isConstructed = true;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
ShowOnScreen(): void {
|
||||
this.AddToViewport(10);
|
||||
}
|
||||
|
||||
CloseAndRelease(): void {
|
||||
this.RemoveFromParent();
|
||||
this.Destruct();
|
||||
this.Release();
|
||||
}
|
||||
|
||||
Destruct(): void {
|
||||
if (this.isDestructed) {
|
||||
return;
|
||||
}
|
||||
this.isDestructed = true;
|
||||
if (this.loadedAsset !== undefined) {
|
||||
UnLua.Unref(this.loadedAsset);
|
||||
this.refProxy = undefined;
|
||||
this.loadedAsset = undefined;
|
||||
}
|
||||
this.weakRef.Reset();
|
||||
}
|
||||
|
||||
HasValidWeakAsset(): boolean {
|
||||
return this.weakRef.IsValid();
|
||||
}
|
||||
|
||||
IsConstructed(): boolean {
|
||||
return this.isConstructed;
|
||||
}
|
||||
|
||||
IsDestructed(): boolean {
|
||||
return this.isDestructed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
/** @noSelfInFile */
|
||||
|
||||
import {
|
||||
Suite,
|
||||
Test,
|
||||
AssertEqual,
|
||||
AssertNear,
|
||||
AssertTrue,
|
||||
AssertFalse,
|
||||
AssertNotNil,
|
||||
AssertArrayEqual,
|
||||
} from "../Harness/TestRunner";
|
||||
import {
|
||||
AdvanceMockTime,
|
||||
CreateBoundInstance,
|
||||
CreateMockMulticastDelegate,
|
||||
CreateMockScriptDelegate,
|
||||
GetMockState,
|
||||
ResetMockState,
|
||||
} from "../Harness/MockUnLuaRuntime";
|
||||
import Ex01_HelloWorld from "./Ex01_HelloWorld";
|
||||
import Ex02_OverrideBlueprintEvents from "./Ex02_OverrideBlueprintEvents";
|
||||
import Ex03_BindDelegates from "./Ex03_BindDelegates";
|
||||
import Ex04_DynamicBinding from "./Ex04_DynamicBinding";
|
||||
import Ex05_BindInputs from "./Ex05_BindInputs";
|
||||
import {
|
||||
VerifyTArrayOperations,
|
||||
VerifyTMapOperations,
|
||||
VerifyTSetOperations,
|
||||
} from "./Ex06_NativeContainers";
|
||||
import Ex07_CallLatentFunction from "./Ex07_CallLatentFunction";
|
||||
import Ex08_StructAndTrace from "./Ex08_StructAndTrace";
|
||||
import Ex09_AssetRefAndUMG from "./Ex09_AssetRefAndUMG";
|
||||
|
||||
export function RunUnLuaExamplesTests(): void {
|
||||
Suite("UnLuaExamples.OfficialPorts", () => {
|
||||
Test("Ex01_HelloWorld: ReceiveBeginPlay prints and logs greeting", () => {
|
||||
ResetMockState();
|
||||
const actor = CreateBoundInstance<Ex01_HelloWorld>(
|
||||
Ex01_HelloWorld as unknown as Record<string, any>,
|
||||
"AActor"
|
||||
);
|
||||
actor.ReceiveBeginPlay();
|
||||
|
||||
AssertTrue(string.find(actor.GetGreeting(), "Hello UnLua from TypeScript", 1, true)[0] !== undefined);
|
||||
AssertEqual(GetMockState().printedStrings.length, 1);
|
||||
AssertEqual(GetMockState().logs.length, 1);
|
||||
});
|
||||
|
||||
Test("Ex02_OverrideBlueprintEvents: lifecycle events and self.Overridden chain", () => {
|
||||
ResetMockState();
|
||||
const actor = CreateBoundInstance<Ex02_OverrideBlueprintEvents>(
|
||||
Ex02_OverrideBlueprintEvents as unknown as Record<string, any>,
|
||||
"AActor"
|
||||
);
|
||||
const other = CreateBoundInstance<UE.AActor>({}, "AActor", { __name: "OtherActor_1" });
|
||||
|
||||
actor.Initialize();
|
||||
actor.UserConstructionScript();
|
||||
actor.ReceiveBeginPlay();
|
||||
actor.ReceiveTick(0.016);
|
||||
actor.ReceiveTick(0.034);
|
||||
actor.ReceiveAnyDamage(35, undefined, undefined, other);
|
||||
actor.ReceiveActorBeginOverlap(other);
|
||||
actor.ReceiveEndPlay(UE.EEndPlayReason.Destroyed);
|
||||
|
||||
AssertNear(actor.GetElapsed(), 0.05);
|
||||
AssertEqual(actor.GetTotalDamage(), 35);
|
||||
AssertEqual(actor.GetOverlapCount(), 1);
|
||||
AssertArrayEqual(actor.GetEvents(), [
|
||||
"Initialize",
|
||||
"UserConstructionScript",
|
||||
"ReceiveBeginPlay",
|
||||
"Damage:35",
|
||||
"Overlap:OtherActor_1",
|
||||
"EndPlay:0",
|
||||
]);
|
||||
AssertEqual(GetMockState().overriddenCalls.length, 7);
|
||||
});
|
||||
|
||||
Test("Ex03_BindDelegates: Multicast, FScriptDelegate and K2_SetTimerDelegate via UnLua.Delegate", () => {
|
||||
ResetMockState();
|
||||
const mockBtn = { OnClicked: CreateMockMulticastDelegate() } as unknown as UE.UButton;
|
||||
const singleDel = CreateMockScriptDelegate();
|
||||
|
||||
const widget = CreateBoundInstance<Ex03_BindDelegates>(
|
||||
Ex03_BindDelegates as unknown as Record<string, any>,
|
||||
"UUserWidget",
|
||||
{
|
||||
ClickMeButton: mockBtn,
|
||||
CustomSingleDelegate: singleDel,
|
||||
}
|
||||
);
|
||||
|
||||
widget.Construct();
|
||||
AssertTrue(mockBtn.OnClicked.IsBound());
|
||||
|
||||
// 触发按钮点击与单播委托
|
||||
mockBtn.OnClicked.Broadcast();
|
||||
mockBtn.OnClicked.Broadcast();
|
||||
AssertEqual(widget.GetClickCount(), 2);
|
||||
AssertEqual(singleDel.Execute(5), 52);
|
||||
|
||||
// 推进定时器 1.6s -> 间隔 0.5s 应触发 3 次
|
||||
AdvanceMockTime(1.6);
|
||||
AssertEqual(widget.GetTimerTickCount(), 3);
|
||||
AssertTrue(UE.UKismetSystemLibrary.K2_IsTimerActiveHandle(widget, widget.GetTimerHandle()));
|
||||
|
||||
// 销毁清理后不应再响应委托或定时器
|
||||
widget.Destruct();
|
||||
AssertFalse(mockBtn.OnClicked.IsBound());
|
||||
mockBtn.OnClicked.Broadcast();
|
||||
AssertEqual(widget.GetClickCount(), 2);
|
||||
|
||||
AdvanceMockTime(2.0);
|
||||
AssertEqual(widget.GetTimerTickCount(), 3);
|
||||
});
|
||||
|
||||
Test("Ex04_DynamicBinding: World:SpawnActor, SpawnActorEx and UE.NewObject with Initializer", () => {
|
||||
ResetMockState();
|
||||
const spawner = CreateBoundInstance<Ex04_DynamicBinding>(
|
||||
Ex04_DynamicBinding as unknown as Record<string, any>,
|
||||
"AActor"
|
||||
);
|
||||
|
||||
const spawned = spawner.SpawnDynamicActor("Fireball", 120);
|
||||
AssertNotNil(spawned);
|
||||
AssertEqual(spawned!.GetInitTag(), "Fireball");
|
||||
AssertEqual(spawned!.GetInitPower(), 120);
|
||||
AssertTrue(spawned!.IsBeginPlayCalled());
|
||||
|
||||
const spawnedEx = spawner.SpawnDynamicActorEx("IceShard");
|
||||
AssertNotNil(spawnedEx);
|
||||
AssertEqual(spawnedEx!.GetInitTag(), "IceShard");
|
||||
AssertEqual(spawnedEx!.GetInitPower(), 77);
|
||||
|
||||
const dynObj = spawner.CreateDynamicObject(10);
|
||||
AssertNotNil(dynObj);
|
||||
AssertEqual(dynObj!.GetSeed(), 10);
|
||||
AssertEqual(dynObj!.NextValue(), 21);
|
||||
AssertEqual(dynObj!.NextValue(), 43);
|
||||
});
|
||||
|
||||
Test("Ex05_BindInputs: UnLua.Input and UnLua.EnhancedInput module registrations", () => {
|
||||
// 模块加载时已注册 5 条输入绑定(2 Key + 1 Action + 1 Axis + 1 EnhancedAction)
|
||||
// 注意:MockState 可能已被前面测试 Reset,此处直接触发已绑定的模块逻辑验证
|
||||
// 重新加载一次模块或直接检查函数执行
|
||||
const pc = CreateBoundInstance<Ex05_BindInputs>(
|
||||
Ex05_BindInputs as unknown as Record<string, any>,
|
||||
"APlayerController"
|
||||
);
|
||||
pc.ReceiveBeginPlay();
|
||||
|
||||
// 重新触发注册表验证(通过 package.loaded 清理后重加载一次)
|
||||
ResetMockState();
|
||||
const pkg = (_G as unknown as Record<string, any>).package as { loaded: Record<string, unknown> };
|
||||
const modName = "Tests.UnLuaExamples.Ex05_BindInputs";
|
||||
const prevMod = pkg.loaded[modName];
|
||||
pkg.loaded[modName] = undefined;
|
||||
require(modName);
|
||||
pkg.loaded[modName] = prevMod;
|
||||
|
||||
const bindings = GetMockState().inputBindings;
|
||||
AssertEqual(bindings.length, 5);
|
||||
AssertEqual(bindings[0].kind, "Key");
|
||||
AssertEqual(bindings[0].name, "SpaceBar");
|
||||
AssertEqual(bindings[1].args?.Ctrl, true);
|
||||
AssertEqual(bindings[2].kind, "Action");
|
||||
AssertEqual(bindings[3].kind, "Axis");
|
||||
AssertEqual(bindings[4].kind, "EnhancedAction");
|
||||
|
||||
// 模拟 UE 分发回调到控制器实例
|
||||
bindings[0].handler.call(pc);
|
||||
AssertEqual(pc.GetLastAction(), "SpaceBar:Pressed");
|
||||
bindings[1].handler.call(pc);
|
||||
AssertEqual(pc.GetLastAction(), "Ctrl+S");
|
||||
bindings[2].handler.call(pc);
|
||||
AssertEqual(pc.GetLastAction(), "Action:Jump");
|
||||
bindings[3].handler.call(pc, 0.75);
|
||||
AssertNear(pc.GetMoveForwardValue(), 0.75);
|
||||
bindings[4].handler.call(pc, -1.0);
|
||||
AssertNear(pc.GetMoveForwardValue(), -1.0);
|
||||
AssertEqual(pc.GetEnhancedCount(), 1);
|
||||
});
|
||||
|
||||
Test("Ex06_NativeContainers: TArray, TMap and TSet full API & pairs()", () => {
|
||||
VerifyTArrayOperations();
|
||||
VerifyTMapOperations();
|
||||
VerifyTSetOperations();
|
||||
});
|
||||
|
||||
Test("Ex07_CallLatentFunction: coroutine Delay sequence & destroy abort guard", () => {
|
||||
ResetMockState();
|
||||
const actor = CreateBoundInstance<Ex07_CallLatentFunction>(
|
||||
Ex07_CallLatentFunction as unknown as Record<string, any>,
|
||||
"AActor"
|
||||
);
|
||||
actor.ReceiveBeginPlay();
|
||||
AssertArrayEqual(actor.GetSteps(), ["Step1:Start"]);
|
||||
AssertFalse(actor.IsCompleted());
|
||||
|
||||
AdvanceMockTime(0.5);
|
||||
AssertArrayEqual(actor.GetSteps(), ["Step1:Start", "Step2:After0.5s"]);
|
||||
AssertFalse(actor.IsCompleted());
|
||||
|
||||
AdvanceMockTime(1.0);
|
||||
AssertArrayEqual(actor.GetSteps(), ["Step1:Start", "Step2:After0.5s", "Step3:Done"]);
|
||||
AssertTrue(actor.IsCompleted());
|
||||
|
||||
// 测试中途销毁:等待期间 Destroy 后恢复协程应安全退出,不再执行后续步骤
|
||||
const doomed = CreateBoundInstance<Ex07_CallLatentFunction>(
|
||||
Ex07_CallLatentFunction as unknown as Record<string, any>,
|
||||
"AActor"
|
||||
);
|
||||
doomed.ReceiveBeginPlay();
|
||||
doomed.K2_DestroyActor();
|
||||
AdvanceMockTime(2.0);
|
||||
AssertArrayEqual(doomed.GetSteps(), ["Step1:Start"]);
|
||||
AssertFalse(doomed.IsCompleted());
|
||||
});
|
||||
|
||||
Test("Ex08_StructAndTrace: FVector math, LineTraceSingle multi-return and K2_SetActorLocation", () => {
|
||||
ResetMockState();
|
||||
const actor = CreateBoundInstance<Ex08_StructAndTrace>(
|
||||
Ex08_StructAndTrace as unknown as Record<string, any>,
|
||||
"AActor"
|
||||
);
|
||||
actor.ReceiveBeginPlay();
|
||||
|
||||
const [size, dot, dist] = actor.ComputeVectorMath();
|
||||
AssertNear(size, 13);
|
||||
AssertNear(dot, 0);
|
||||
AssertNear(dist, 13);
|
||||
|
||||
AssertTrue(actor.TeleportTo(100, 0, 50));
|
||||
const [bHit, hitDist, impact] = actor.TraceForward(200);
|
||||
AssertTrue(bHit);
|
||||
AssertNear(hitDist, 100);
|
||||
AssertNear(impact.X, 200);
|
||||
AssertNear(impact.Z, 50);
|
||||
});
|
||||
|
||||
Test("Ex09_AssetRefAndUMG: UObject.Load, UnLua.Ref/Unref, WeakPtr and UMG Release", () => {
|
||||
ResetMockState();
|
||||
const widget = CreateBoundInstance<Ex09_AssetRefAndUMG>(
|
||||
Ex09_AssetRefAndUMG as unknown as Record<string, any>,
|
||||
"UUserWidget"
|
||||
);
|
||||
widget.Initialize();
|
||||
widget.Construct();
|
||||
widget.ShowOnScreen();
|
||||
|
||||
AssertTrue(widget.IsConstructed());
|
||||
AssertFalse(widget.IsDestructed());
|
||||
AssertTrue(widget.HasValidWeakAsset());
|
||||
|
||||
widget.CloseAndRelease();
|
||||
AssertTrue(widget.IsDestructed());
|
||||
AssertFalse(widget.HasValidWeakAsset());
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user