工具脚本(Util Scripts)
工具脚本(Util Scripts)用于把可复用逻辑拆分为小模块,并在多个脚本间共享。
非常适合数学工具、几何函数、颜色工具等辅助逻辑。
创建工具脚本
创建新脚本 并选择 工具(Util) 类型。
--- Example helper function.
local function add(a: number, b: number): MyUtil
return a + b,
end
-- Return the functions you'd like to use in another script
return {
add = add,
}
用法(Usage):
local MyUtil = require("MyUtil")
local result = MyUtil.add(2, 3)
print(result) -- 5
带自定义类型的工具脚本
在 Util 脚本中定义的自定义类型(Custom Types)可在引用脚本中直接使用。
--- Defines the return type for this util.
--- The type is automatically available when you require the script.
export type AdditionResult = {
exampleValue: number,
someString: string
}
--- Example helper function.
local function add(a: number, b: number): AdditionResult
return {
exampleValue = a + b,
someString = "4 out of 5 dentists recommend Rive"
}
end
return {
add = add,
}
用法(Usage):
-- With type annotation
local result: AdditionResult = MyUtil.add(2, 3)