MemoryStoreHashMap
*Konten ini diterjemahkan menggunakan AI (Beta) dan mungkin mengandung kesalahan. Untuk melihat halaman ini dalam bahasa Inggris, klik di sini.
Memberikan akses ke peta hash dalam MemoryStoreService waktu.Peta hash adalah koleksi item di mana kunci string terkait dengan nilai acak (hingga ukuran maksimum yang diizinkan -- lihat Toko Memori).Kunci tidak memiliki jaminan pemesanan.
Rangkuman
Metode
Mengambil nilai kunci di peta hash.
Kembalikan objek MemoryStoreHashMapPages untuk menguraikan melalui item di peta hash.
Menghapus item dari peta hash.
Mengatur nilai kunci di peta hash.
Ambil nilai kunci dari peta hash dan memungkinkan Anda untuk memperbaruinya ke nilai baru.
Properti
Metode
GetAsync
Mengambil nilai kunci di peta hash.
Parameter
Kunci yang nilainya ingin Anda mengambil.
Memberikan nilai
Nilai, atau nil jika kunci tidak ada.
Contoh Kode
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
Kembalikan objek MemoryStoreHashMapPages untuk menguraikan melalui item di peta hash. Jarak yang valid adalah 1 hingga 200 termasuk.
Parameter
Jumlah maksimum item yang bisa dikembalikan.
Memberikan nilai
Sebuah instansi MemoryStoreHashMapPages yang mencantumkan item sebagai MemoryStoreHashMapPages instansi.
Contoh Kode
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
Menghapus item dari peta hash.
Parameter
Kunci untuk menghapus.
Memberikan nilai
Contoh Kode
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
Tetapkan nilai kunci di peta hash, menghapus nilai yang ada.
Parameter
Kunci yang nilainya untuk atur.
Nilai untuk atur.
Item kedaluwarsa dalam beberapa detik, setelah itu item secara otomatis dihapus dari peta hash.Waktu kedaluwarsa maksimum adalah 45 hari (3.888.000 detik).
Memberikan nilai
Contoh Kode
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
Ambil nilai kunci dari peta hash dan memungkinkan Anda untuk memperbaruinya ke nilai baru.
Metode ini menerima fungsi panggil balas yang memperoleh nilai kunci yang ada dan mengirimkannya ke fungsi transformasi, yang mengembalikan nilai baru untuk item, dengan pengecualian berikut:
- Jika kunci tidak ada, nilai lama yang dikirim ke fungsi adalah nil .
- Jika fungsi mengembalikan nil, pembaruan dibatalkan.
Nilai baru disimpan hanya jika kunci tidak diperbarui (misalnya, oleh server permainan yang berbeda) sejak saat dilihat.Jika nilai berubah pada saat itu, fungsi transformasi dipanggil lagi dengan nilai item terbaru.Siklus ini diulang sampai nilai disimpan dengan sukses atau fungsi transformasi kembali nil untuk membatalkan operasi.
Parameter
Kunci yang nilainya ingin Anda update.
Fungsi transformasi, yang Anda menyediakan. Fungsi ini mengambil nilai lama sebagai input dan kembalikan nilai baru.
Item kedaluwarsa dalam beberapa detik, setelah itu item secara otomatis dihapus dari peta hash.Waktu kedaluwarsa maksimum adalah 45 hari (3.888.000 detik).
Memberikan nilai
Nilai terakhir yang dikembalikan oleh fungsi transformasi.
Contoh Kode
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)