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
|
||||
Reference in new issue
Block a user