A ModuleScript 는 호출로 require() 에 정확히 하나의 값을 반환하는 스크립트 유형입니다.루오 환경당 한 번만 실행하고 나중에 에 대한 후속 호출에 정확히 같은 값을 반환합니다.
ModuleScripts는 "자신을 반복하지 마십시오"(DRY) 원칙을 준수하기 위한 필수 개체로, 한 번만 함수를 작성하고 모든 곳에서 사용할 수 있습니다.함수의 여러 복사본을 가지고 있으면 동작을 변경해야 할 때 문제가 될 수 있으므로 함수 또는 함수 그룹을 에 정의하고 해당 모듈에서 및 호출을 수행해야 합니다.
ModuleScripts 에서 반환되는 값은 Scripts 및 LocalScripts와 독립적이며, 명령 모음과 같은 다른 환경과도 독립적입니다.클라이언트에서 를 사용하여 에서 코드를 실행하면 서버에서 이미 를 수행했더라도 클라이언트에서 코드가 실행됩니다.따라서 클라이언트와 서버에서 동시에 ModuleScript를 사용하거나 Studio에서 디버깅하는 경우 주의하십시오.
에 대한 첫 번째 호출은 에서 생성되지 않으면 (중지) 되지 않으며, 이 경우 현재 스레드가 에서 호출하여 을 생성할 때까지 생성됩니다. 가 다른 을 시도하고 있는 경우, 스레드는 중단되지 않고 결코 중지되지 않습니다(순환 호출은 오류를 생성하지 않음).대형 프로젝트에서 모듈 종속성을 주의하십시오!
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를 사용하여 스크립트 편집기와 상호작용하는 것을 고려하십시오.