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进行必要操作。然后它可以加载到你的体验中,虽然这个逻辑仅在服务器上运行,并且在客户端上会出错。如果其他用户想使用模块,它必须是公开共的。
代码示例
代码示例首先创建一个本地变量,包含一个空表。然后它用两个占位符函数填充表,最后返回表。在模块脚本中使用此代码将使 my_functions 表(以及其中的任何函数、表或其他值)对任何脚本、本地脚本或其他模块脚本可用。
-- 表存储多个值在一个变量中
local MyFunctions = {}
-- 向表中添加几个函数
function MyFunctions.foo()
print("Foo!")
end
function MyFunctions.bar()
print("Bar!")
end
-- 模块脚本必须返回一个值
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()