概要
函式
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
範例程式碼
獲取元表
local meta = {}
local t = setmetatable({}, meta)
print(getmetatable(t) == meta) --> true
-- 通過設置 __metatable 元方法使原始元表無法恢復:
meta.__metatable = "受保護"
print(getmetatable(t)) --> protectedipairs
loadstring
pairs
pcall
返回
範例程式碼
Pcall
local function divideByFive(n: number): number
return n / 5
end
local success, errorMessage = pcall(divideByFive, "notANumber") -- 會導致錯誤...
if success then
-- 處理成功的回應...
else
print("錯誤訊息:", errorMessage)
endrequire
參數
返回
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)select
setfenv
setmetatable
參數
newMeta:Variant |
返回
範例程式碼
設置元表
local meta = {__metatable = "protected"}
local t = {}
setmetatable(t, meta) -- 這會設置 t 的元表
-- 我們現在有一個表 t,並且有一個元表。如果我們嘗試更改它...
local ok, err = pcall(setmetatable, t, {})
assert(not ok and err:find("protected")) -- 錯誤:無法更改受保護的元表tonumber
參數
arg:Variant |
| 預設值:10 |
返回
Variant
範例程式碼
轉換為數字
print(tonumber("1337")) --> 1337 (假設基數為 10,十進制)
print(tonumber("1.25")) --> 1.25 (基數 10 可能有小數部分)
print(tonumber("3e2")) --> 300 (基數 10 可能有指數部分,3 × 10 ^ 2)
print(tonumber("25", 8)) --> 21 (基數 8,八進制)
print(tonumber("0x100")) --> 256 (假設基數為 16,十六進制)
print(tonumber("roblox")) --> nil (不會引發錯誤)
-- 提示:如果您希望無法轉換的數字引發錯誤,請與 assert 一起使用
local ok, err = pcall(function() assert(tonumber("roblox")) end)
print(ok and "成功" or "錯誤: " .. tostring(err)) --> 錯誤: 斷言失敗tostring
unpack
屬性