A ModuleScript 是一个脚本类型,通过调用 require() 返回一个值。ModuleScripts,每个 Luau 环境只运行一次,返回与后续调用相同的值给 require()。
ModuleScripts 是遵守“不要重复自己”(DRY)原则的必要对象,可以让你只写一次函数并在所有地方使用它。当需要更改函数的行为时,拥有多个副本的函数会很麻烦,因此您应该在 ModuleScripts 中定义函数或函数组,并让 Scripts 和 LocalScripts 调用 require() 在那些模块上。
从 ModuleScripts 返回的值独立于 Scripts 和 LocalScripts 以及其他环境,例如 命令栏 。在 上使用 将在 上运行代码,即使 已在服务器上执行过。因此,如果您同时使用客户端和服务器上的 ModuleScript,或在 Studio 中调试它,请注意安全。
请注意,第一次调用 require() 将无法产生(停止),除非 ModuleScript 产生(例如调用 task.wait() ),在这种情况下,调用 require() 的当前线程将继续产生直到 ModuleScript 返回值。如果 试图 另一个 ,那么线程将挂起并永远不会停止 (循环 调用不会生成错误)。在大型项目中注意您的模块依赖!
如果 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()