ModuleScript
*このコンテンツは、ベータ版のAI(人工知能)を使用して翻訳されており、エラーが含まれている可能性があります。このページを英語で表示するには、 こちら をクリックしてください。
A ModuleScript は、require() による呼び出しで正確に 1つの値を返すスクリプトタイプです。ModuleScripts ルアウ環境ごとに一度だけ実行し、次の呼び出しに同じ値を返す require() 。
ModuleScripts は「自分を繰り返さない」(DRY) 原則に従うための必須のオブジェクトであり、1度だけ機能を書き、どこでも使用できます。機能の複数のコピーを持つことは、その動作を変更する必要があるときに問題があるため、 で機能または機能グループを定義し、それらのモジュールで と の呼び出しを行う必要があります。
返り値が ModuleScripts から Scripts および LocalScripts と独立していることを知ることは重要です。コマンドバー のような他の環境も含まれます。クライアント上でコードを実行するには、require() を使用して、ModuleScript 内の LocalScript でも、Script がすでにサーバー上でそうしていても、コードを実行します。ため、クライアントとサーバーの両方で ModuleScript を使用しているか、または Studio 内でデバッグしている場合は注意してください。
最初の require() への呼び出しは、ModuleScript が生成しない限り、task.wait() が生成しない限り、現在のスレッドが require() を返すまで生成しないことに注意してください。この場合、ModuleScript が値を返すまで、現在のスレッドが生成します。If a が別の を試みている場合、スレッドは を持続し、停止しない (サイクリック 呼び出しはエラーを生成しません)。大規模プロジェクトでモジュールの依存関係に注意してください!
Roblox に ModuleScript がアップロードされ、ルートモジュールの名前が MainModule に設定されている場合、モデルとしてアップロードし、モデルのアセットIDで require() を使用する必要があります。その後、このロジックはサーバーでのみ動作し、クライアントでエラーが発生しますが、エクスペリエンスにロードできます。他のユーザーがモジュールを使用したい場合、公開でなければなりません。
コードサンプル
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()
概要
プロパティ
Source
実行するコード。
ユーザーが開いているスクリプトを読んだり変更したい場合は、代わりに ScriptEditorService を使用してスクリプトエディタと対話することを検討してください。