test: add comprehensive ts2lua-unreal TS/Lua 5.4 test suites and upgrade to v0.2.2

This commit is contained in:
szy73711 committed 2026-11-29 03:35:49 +08:00
1 parent ee2e62bb34
commit 3dd61c32a9
75 files changed
+9929 -10

No files matched your search

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