ModuleScript
*Nội dung này được dịch bằng AI (Beta) và có thể có lỗi. Để xem trang này bằng tiếng Anh, hãy nhấp vào đây.
ModuleScript là một loại contender Lua source thực thi một lần và phải trả lại chính xác một giá trị. Giá trị này sau đó được trả lại bằng một cuộc gọi đến require được cho là contender duy nhất. CácModuleScripts chạy một lần và chỉ một lần mỗi môi trường
ModuleScripts là những thực thể cần thiết để tuân theo nguyên tắc không lặp lại chính mình (DRY). Khi bạn viết một hàm, viết nó chỉ một lần và sử dụng nó ở khắp mọi nơi. Khi bạn có nhiều bản sao của mộ
Quan trọng là phải biết rằng giá trị trả từModuleScripts là độc lập về mặt địa phương với LocalScript và Scripts, và các môi trường khác như Cửa hàng Command. Sử dụng
Lưu ý rằng cuộc gọi đầu tiên đến require trên một ModuleScript sẽ k
Nếu một Class.ModuleScript được tải lên Roblox và modul chính có tên được thiết lập là ModuleScript , nó có thể được tải lên như một mô hình và yêu cầu bằng cách sử dụ
Mẫu mã
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()
Tóm Tắt
Thuộc Tính
Mã để thi hành.
Thuộc Tính
Source
Mã để thi hành.
Nếu bạn muốn đọc hoặc chỉnh sửa một script mà người dùng đã mở, hãy xem xét sử dụng ScriptEditorService để tương tác với Editor Script thay vào đó.