代表一個可以在執行上下文之間共享的表-like 資料結構。雖然它可以用於各種一般資料存取,但它的設計是專為 並行 Luau 使用,在不同 Actor 實例下,可以用來在脚本中分享狀態。
有幾種語言方式可以在指令碼之間通信共享表。其中一種方法是存儲和取回 SharedTable 對象在 SharedTableRegistry 。寄存庫允許任何資料模型內的任何指令碼獲得或設定 <
像 Luau 桌子一樣,SharedTable 對象存儲一組鑰匙值元素對。與 Luau 桌子不同,只有選擇的對象類型才能在共享桌子中儲存,與 Roblox 引擎的其他限制類似。
鑰匙必須是 (1) 一個字串或 (2) 一個不為零的整數數量小於 2 32 。 其他類型的鑰匙不是支持的。
值必須是以下類型之一:Boolean、Number、Vector、String、SharedTable 或串行化的數據輸入。 能夠將 SharedTable 作為值在另一個 SharedTable 中的存儲,允許建立階層狀結構的數據結構。
SharedTable 對象是獨立的且不相同的 SharedTable 對象永遠不會比平等,即使有內容,即使它們有內容也不會比平等。
喜歡一個 Luau 桌子,一個 SharedTable 對象可能會凍結,在此情況下它只能閱取。嘗試修改凍結的 Datatype.SharedTable</
範例程式碼
Element Access
local st = SharedTable.new()
st[1] = "a"
st["x"] = true
st.y = 5
assert(st[1] == "a")
assert(st["x"] == true)
assert(st.x == true)
assert(st["y"] == 5)
assert(st.y == 5)
-- true is not a valid SharedTable key, so attempting to set that key
-- fails:
assert(not pcall(function() st[true] = 100 end))
-- A function is not a valid SharedTable value, so attempting to set a
-- value to a function fails:
assert(not pcall(function() st["f"] = function() end end))
Element Iteration
local st = SharedTable.new({"a", "b", "c"})
for k, v in SharedTable.clone(st, false) do
print(k, ": ", v)
end
for k, v in st do
print(k, ": ", v)
end
概要
函式
建構子
new
函式
clone
參數
預設值:false
範例程式碼
Shallow Clone
local original = SharedTable.new()
original["a"] = "original a"
original["b"] = "original b"
original["c"] = SharedTable.new()
original["c"]["d"] = "original d"
local clone = SharedTable.clone(original, false)
clone["a"] = "new a"
clone["b"] = "new b"
clone["c"]["d"] = "new d"
assert(original["a"] == "original a")
assert(original["b"] == "original b")
-- Because this was a shallow clone, original["c"] and clone["c"] are
-- the same SharedTable object.
assert(original["c"] == clone["c"])
assert(original["c"]["d"] == "new d")
Deep Clone
local original = SharedTable.new()
original["a"] = "original a"
original["b"] = "original b"
original["c"] = SharedTable.new()
original["c"]["d"] = "original d"
local clone = SharedTable.clone(original, true)
clone["a"] = "new a"
clone["b"] = "new b"
clone["c"]["d"] = "new d"
assert(original["a"] == "original a")
assert(original["b"] == "original b")
-- Because this was a deep clone, clone["c"] is a clone of original["c"];
-- they are distinct SharedTable objects.
assert(original["c"] ~= clone["c"])
assert(original["c"]["d"] == "original d")
increment
參數
返回
範例程式碼
Increment
local st = SharedTable.new()
st["x"] = 1
local oldValue = SharedTable.increment(st, "x", 1)
assert(oldValue == 1)
assert(st["x"] == 2)
-- The value of the specified key must be a number. If it is not a
-- number, the call will fail:
st["y"] = "test"
assert(not pcall(function() SharedTable.increment(st, "y", 1) end))
update
void
參數
返回
void
範例程式碼
Update
local st = SharedTable.new()
st["x"] = "abcd"
SharedTable.update(st, "x", function(v)
assert(v == "abcd")
return v .. "e"
end)
assert(st["x"] == "abcde")