在 MemoryStoreService 內提供存取哈希地圖。哈希地圖是一個包含字串鑰匙與隨機值相關的物品集(直到允許的最大尺寸--參見記憶儲存)。鍵沒有排序保證。
概要
方法
在哈希地圖中取得鑰匙的值。
返回一個 MemoryStoreHashMapPages 對象來枚舉通過哈希地圖中的項目。
從哈希地圖中移除一個項目。
設置哈希地圖中鑰匙的值。
從哈希地圖中取得鑰匙的值,並讓您將其更新為新值。
屬性
方法
GetAsync
在哈希地圖中取得鑰匙的值。
參數
值為您想要擷取的鑰匙。
返回
值或nil如果鑰匙不存在。
範例程式碼
local MemoryStoreService = game:GetService("MemoryStoreService")
local hashMap = MemoryStoreService:GetHashMap("HashMap1")
local key = "User_1234"
local value = 1000
local expiration = 30
local setSuccess, _ = pcall(function()
return hashMap:SetAsync(key, value, expiration)
end)
if setSuccess then
print("Set succeeded!")
end
local item
local getSuccess, getError = pcall(function()
item = hashMap:GetAsync(key)
end)
if getSuccess then
print(item)
else
warn(getError)
end
ListItemsAsync
返回一個 MemoryStoreHashMapPages 對象來枚舉通過哈希地圖中的項目。有效範圍為 1 到 200 包括。
參數
最大可返回的項目數量。
返回
範例程式碼
The code below lists all the items in a Memory Store Hash Map.
local MemoryStoreService = game:GetService("MemoryStoreService")
local testHashMap = MemoryStoreService:GetHashMap("HashMap1")
local EXPIRATION = 600
local NUM_TEST_ITEMS = 32
local function populateHashMap(hashMap: MemoryStoreHashMap, numItems: number): { [string]: any }
print("Setting HashMap data...")
local createdItems = {}
for index = 1, numItems do
local key = tostring(index) -- HashMap keys must be strings
local value = `{key}_test_value`
local success, result = pcall(hashMap.SetAsync, hashMap, key, value, EXPIRATION)
if success then
createdItems[key] = value
else
warn(`Error setting key {key}: {result}`)
end
end
print("Done setting HashMap data.")
return createdItems
end
local function getItemsFromAllPages(pages: MemoryStoreHashMapPages): { [string]: any }
-- Purely for logging purposes, we track what page number we're on
local currentPageNumber = 1
local retrievedItems = {}
while not pages.IsFinished do
print(`Getting items on page {currentPageNumber}...`)
local items = pages:GetCurrentPage()
for _, entry in pairs(items) do
print(`\t{entry.key}: {entry.value}`)
retrievedItems[entry.key] = entry.value
end
-- Advance pages if there are more pages to read
if not pages.IsFinished then
pages:AdvanceToNextPageAsync()
currentPageNumber += 1
end
end
print("Finished reading all pages")
return retrievedItems
end
local function compareAllItems(retrievedItems: { [string]: any }, expectedItems: { [string]: any }): number
print("Comparing retrieved items to expected items...")
local numMatchingItems = 0
for key, expectedValue in pairs(expectedItems) do
if retrievedItems[key] == expectedValue then
numMatchingItems += 1
else
warn(`Mismatched retrieved value for key {key}: expected {expectedValue}, retrieved {retrievedItems[key]}`)
end
end
print("Comparison complete!")
return numMatchingItems
end
-- Keys added to the hashmap are also added to this expectedItems table.
-- Later, the retrieved hashmap items will be compared against this table of expected items.
local expectedItems = populateHashMap(testHashMap, NUM_TEST_ITEMS)
-- Getting pages can error. In this case, we will let it error and stop program execution,
-- but you may want to pcall it and handle it differently.
print(`Getting HashMap pages with ListItemsAsync...`)
local pages = testHashMap:ListItemsAsync(NUM_TEST_ITEMS)
local retrievedItems = getItemsFromAllPages(pages)
local numMatchingItems = compareAllItems(retrievedItems, expectedItems)
-- If there were no errors setting or getting items, all items should match.
print(`Program complete. {numMatchingItems}/{NUM_TEST_ITEMS} retrieved items matched the expected values.`)
RemoveAsync
從哈希地圖中移除一個項目。
參數
要移除的關鍵。
返回
範例程式碼
local MemoryStoreService = game:GetService("MemoryStoreService")
local hashMap = MemoryStoreService:GetHashMap("HashMap1")
local key = "User_1234"
local value = 1000
local expiration = 30
local setSuccess, setError = pcall(function()
return hashMap:SetAsync(key, value, expiration)
end)
if not setSuccess then
warn(setError)
end
local removeSuccess, removeError = pcall(function()
hashMap:RemoveAsync(key)
end)
if removeSuccess then
print("Remove succeeded!")
else
warn(removeError)
end
SetAsync
在哈希地圖中設置鑰匙的值,覆蓋任何現有值。
參數
要設設定的值的鑰匙。
要設定置的值。
項目在幾秒鐘後到期,項目將自動從哈希地圖中移除。最長有效時間為 45 天 (3,888,000 秒)。
返回
範例程式碼
local MemoryStoreService = game:GetService("MemoryStoreService")
local hashMap = MemoryStoreService:GetHashMap("HashMap1")
local key = "User_1234"
local value = 1000
local expiration = 30
local setSuccess, setError = pcall(function()
return hashMap:SetAsync(key, value, expiration)
end)
if setSuccess then
print("Set succeeded!")
else
warn(setError)
end
UpdateAsync
從哈希地圖中取得鑰匙的值,並讓您將其更新為新值。
這個方法接受一個回呼功能,會擷取現有的鑰匙值並將其傳給轉換功能,該功能會為道具目返回新值,但有以下例外:
- 如果鑰匙不存在,傳給函數的舊值是 nil 。
- 如果函數返回 nil,更新將被取消。
新值只會儲存,如果鑰匙從閱已讀時刻起未更新(例如,由不同的遊戲伺服器更新)。如果在那個時間值發生變更,變換功能會再次呼叫最新項目值。此循環會繼續重複,直到值成功儲存或變換函數返回 nil 以取消操作。
參數
值為您想要更新的鑰匙。
你提供的變換功能。這個功能會將舊值作為輸入,並返回新值。
項目在幾秒鐘後到期,項目將自動從哈希地圖中移除。最長有效時間為 45 天 (3,888,000 秒)。
返回
變換函數返回的最後值。
範例程式碼
This sample updates the count of some resource in a shared inventory. The use of MemoryStoreHashMap:UpdateAsync() ensures that all player contributions make their way into this shared inventory, even if the contributions occur simultaneously. The function enforces a max resource count of 500.
local MemoryStoreService = game:GetService("MemoryStoreService")
local hashMap = MemoryStoreService:GetHashMap("ResourceInventory")
local function contributeResources(itemResource, addedCount)
local success, newResourceCount = pcall(function()
return hashMap:UpdateAsync(itemResource, function(resource)
resource = resource or { count = 0 }
resource.count = resource.count + addedCount
-- ensure we don't exceed the maximum resource count
if resource.count > 500 then
resource.count = 500
end
return resource
end, 1200)
end)
if success then
print(newResourceCount)
end
end
contributeResources("myResource", 50)