A ModuleScript 是一種類型的腳本,通過呼叫 require() 返回一個值。ModuleScripts 每個 Luau 環境只能執行一次,並且只能返回相同的值給後續呼叫 require() 。
ModuleScripts 是遵守「不要重複自己」(DRY)原則的必要物件,讓您只需寫一次函數並在所有地方使用它。當需要更改功能的行為時,複製多個功能會很麻煩,因此您應該在 ModuleScripts 中定義功能或功能組,並讓 Scripts 和 LocalScripts 呼叫 require() 在那些模組上。
重要的是要知道,從 ModuleScripts 返回的值獨立於 Scripts 和 LocalScripts 以及其他環境,例如 指令欄 。在 上使用 將在服務器上執行代碼,即使 已在服務器上執行過,也是如此。因此,如果您同時在客戶端和伺服器上使用 ModuleScript,或在 Studio 中嘗試偵錯,請小心。
請注意,第一次呼叫 require() 將不會產生(停止),除非 ModuleScript 產生(例如呼叫 task.wait() ),在此情況下,當前呼叫 require() 的線程將會持續直到 ModuleScript 返回值。如果 ModuleScript 正在嘗試 require() 另一個 ModuleScript ,那在轉而嘗試 require() 它時,線程將 掛住並永遠停止 (循環 require() 呼叫不會生成錯誤)。在大型項目中注意模組依存關係!
如果 ModuleScript 被上傳到 Roblox,根模組的名稱設為 MainModule,它可以作為模型上傳,並需要使用 require() 的模型資產ID來使用。然後它可以加載到您的體驗中,雖然這個邏輯只適用於服務器,並且在客戶端上會發生錯誤。如果其他使用者想使用模組,它必須是公開的。
範例程式碼
The code sample starts by creating a local variable holding an empty table. It then fills the table with two placeholder functions, and then finally returns the table. Using this code in a ModuleScript would make the my_functions table (and thus any functions, tables or other values within it) available to any Script, LocalScript or other ModuleScript.
-- Tables store multiple values in one variable
local MyFunctions = {}
-- Add a few functions to the table
function MyFunctions.foo()
print("Foo!")
end
function MyFunctions.bar()
print("Bar!")
end
-- ModuleScripts must return exactly one value
return MyFunctions
This code sample shows how to use the require function on a ModuleScript, then use the value that it returned. See the "Simple ModuleScript Example" for the code to go with this sample.
-- The require function is provided a ModuleScript, then runs
-- the code, waiting until it returns a singular value.
local MyFunctions = require(script.Parent.MyFunctions)
-- These are some dummy functions defined in another code sample
MyFunctions.foo()
MyFunctions.bar()