範例程式碼
在 MemoryStore 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("設定 HashMap 數據...")
local createdItems = {}
for index = 1, numItems do
local key = tostring(index) -- HashMap 鍵必須是字串
local value = `{key}_test_value`
local success, result = pcall(hashMap.SetAsync, hashMap, key, value, EXPIRATION)
if success then
createdItems[key] = value
else
warn(`設置鍵 {key} 時發生錯誤: {result}`)
end
end
print("完成設置 HashMap 數據.")
return createdItems
end
local function getItemsFromAllPages(pages: MemoryStoreHashMapPages): { [string]: any }
-- 僅用於日誌記錄,我們追蹤當前的頁面號碼
local currentPageNumber = 1
local retrievedItems = {}
while not pages.IsFinished do
print(`正在獲取第 {currentPageNumber} 頁的項目...`)
local items = pages:GetCurrentPage()
for _, entry in pairs(items) do
print(` {entry.key}: {entry.value}`)
retrievedItems[entry.key] = entry.value
end
-- 如果還有更多頁面,則推進頁面
if not pages.IsFinished then
pages:AdvanceToNextPageAsync()
currentPageNumber += 1
end
end
print("完成閱讀所有頁面")
return retrievedItems
end
local function compareAllItems(retrievedItems: { [string]: any }, expectedItems: { [string]: any }): number
print("正在比較獲取的項目和預期項目...")
local numMatchingItems = 0
for key, expectedValue in pairs(expectedItems) do
if retrievedItems[key] == expectedValue then
numMatchingItems += 1
else
warn(`鍵 {key} 的獲取值不匹配: 預期 {expectedValue}, 獲取 {retrievedItems[key]}`)
end
end
print("比較完成!")
return numMatchingItems
end
-- 添加到 hashmap 的鍵也會添加到此 expectedItems 表中。
-- 稍後,獲取的 hashmap 項目將與這個預期項目表進行比較。
local expectedItems = populateHashMap(testHashMap, NUM_TEST_ITEMS)
-- 獲取頁面可能會出錯。在這種情況下,我們將讓它出錯並停止程序執行,
-- 但您可能希望使用 pcall 來處理它。
print(`正在使用 ListItemsAsync 獲取 HashMap 頁面...`)
local pages = testHashMap:ListItemsAsync(NUM_TEST_ITEMS)
local retrievedItems = getItemsFromAllPages(pages)
local numMatchingItems = compareAllItems(retrievedItems, expectedItems)
-- 如果設置或獲取項目時沒有錯誤,則所有項目應該匹配。
print(`程序完成。{numMatchingItems}/{NUM_TEST_ITEMS} 獲取的項目匹配預期值.`)