MemoryStoreHashMap
*Bu içerik, tercih ettiğin dilde çok yakında mevcut olacak.
Provides access to a hash map within MemoryStoreService. A hash map is a collection of items where string keys are associated with arbitrary values (up to the maximum allowed size -- see Memory Stores). The keys have no ordering guarantees.
Özet
Özellikler
Yöntemler
Retrieves the value of a key in the hash map.
Returns a MemoryStoreHashMapPages object for enumerating through items in the hash map.
Removes an item from the hash map.
Sets the value of a key in the hash map.
Retrieves the value of a key from a hash map and lets you update it to a new value.
Özellikler
Yöntemler
GetAsync
Retrieves the value of a key in the hash map.
Parametreler
The key whose value you want to retrieve.
Dönüşler
The value, or nil if the key doesn't exist.
Kod Örnekleri
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
Returns a MemoryStoreHashMapPages object for enumerating through items in the hash map. The valid range is 1 to 200 inclusive.
Parametreler
Maximum possible number of items that can be returned.
Dönüşler
A MemoryStoreHashMapPages instance that enumerates the items as MemoryStoreHashMapPages instances.
Kod Örnekleri
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
Removes an item from the hash map.
Parametreler
The key to remove.
Dönüşler
Kod Örnekleri
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
Sets the value of a key in the hash map, overwriting any existing value.
Parametreler
The key whose value to set.
The value to set.
Item expiration in seconds, after which the item is automatically removed from the hash map. The maximum expiration time is 45 days (3,888,000 seconds).
Dönüşler
Kod Örnekleri
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
Retrieves the value of a key from a hash map and lets you update it to a new value.
This method accepts a callback function that retrieves the existing key value and passes it to a transform function, which returns the new value for the item, with these exceptions:
- If the key does not exist, the old value passed to the function is nil.
- If the function returns nil, the update is canceled.
The new value is saved only if the key was not updated (for example, by a different game server) since the moment it was read. If the value changed in that time, the transform function is called again with the most recent item value. This cycle repeats until the value is saved successfully or the transform function returns nil to abort the operation.
Parametreler
The key whose value you want to update.
The transform function, which you provide. This function takes the old value as an input and returns the new value.
Item expiration in seconds, after which the item is automatically removed from the hash map. The maximum expiration time is 45 days (3,888,000 seconds).
Dönüşler
The last value returned by the transform function.
Kod Örnekleri
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)