Luau globals
*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡。
概要
函式
collectgarbage(operation: string):Variant |
getmetatable(t: Variant):Variant |
loadstring(contents: string,chunkname: string):Variant |
require(module: ModuleScript | string | number):Variant |
setmetatable(t: table,newMeta: Variant):table |
API 參考
函式
assert
collectgarbage
getfenv
getmetatable
getmetatable(t:Variant):Variant
參數
t:Variant |
返回
Variant
範例程式碼
獲取元表
loadstring
返回
Variant
範例程式碼
載入字串
-- 必須在 ServerScriptService 中啟用 LoadStringEnabled
local compiled, errorMessage = loadstring("return 1 + 2")
if compiled then
print(compiled()) --> 3
else
print("載入失敗:", errorMessage)
end
-- 無效的代碼返回 nil 及錯誤訊息
local broken, syntaxError = loadstring("return +")
print(broken, syntaxError) --> nil <語法錯誤>next
pcall
rawset
require
參數
返回
Variant
範例程式碼
需要模組解析
-- "./" 前綴等同於 script.Parent
require("./MySibling")
require((script.Parent).MySibling)
-- "../" 前綴等同於 script.Parent.Parent
require("../SiblingOfMyParent")
require((script.Parent.Parent).SiblingOfMyParent)
-- "../" 可以鏈接以向上多層
require("../../SiblingOfMyGrandparent")
require((script.Parent.Parent).Parent.SiblingOfMyGrandparent)
-- "@self" 前綴對應於腳本本身
require("@self/MyChild")
require((script).MyChild)
-- "@game" 前綴對應於 DataModel 根
require("@game/ReplicatedStorage/Shared/MyModule")
require((game).ReplicatedStorage.Shared.MyModule)setfenv
unpack
屬性
_ G
範例程式碼
與 _G 共享值
-- 腳本 A 將一個值存儲在 _G 中
_G.mySharedValue = "來自腳本 A 的問候"
-- 腳本 B 在相同的上下文級別運行,可以讀取它
print(_G.mySharedValue) --> 來自腳本 A 的問候
-- 任何函數也可以讀取和更新共享狀態
_G.counter = (_G.counter or 0) + 1
print(_G.counter) --> 1