MemoryStoreHashMap

Visualizza obsoleti

*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.

Non costruibile
Non Replicato

Fornisce l'accesso a una mappa di hash entro MemoryStoreService .Una mappa di hash è una raccolta di elementi in cui le chiavi di stringa sono associate a valori arbitrari (fino alla dimensione massima consentita -- vedi Magazzini di memoria).Le chiavi non hanno garanzie di ordinamento.

Sommario

Metodi

Proprietà

Metodi

GetAsync

Variant
Resa

Recupera il valore di una chiave nella mappa hash.

Parametri

key: string

La chiave il cui valore vuoi Recuperare.

Valore predefinito: ""

Restituzioni

Variant

Il valore, o nil se la chiave non esiste.

Campioni di codice

Getting data from a MemoryStore Hash Map

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
Resa

Restituisce un oggetto MemoryStoreHashMapPages per l'elencazione attraverso gli elementi nella mappa hash. Il range valido è 1 a 200 inclusi.

Parametri

count: number

Numero massimo di oggetti possibili da restituire.

Valore predefinito: ""

Restituzioni

Un'istanza MemoryStoreHashMapPages che elenca gli elementi come MemoryStoreHashMapPages istanze.

Campioni di codice

Il codice seguente elenca tutti gli elementi in una mappa Hash del Memory Store.

Elencare gli elementi in una mappa Hash di MemoryStore

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) -- Le chiavi della mappa devono essere stringhe
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 }
-- Solo per scopi di registrazione, tracciamo quale numero di pagina siamo
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
-- Pagine di avanzamento se ci sono più pagine da leggere
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
-- Le chiavi aggiunte alla mappa hash vengono anche aggiunte a questa tabella di oggetti attesi.
-- In seguito, gli elementi della mappa hash recuperati verranno confrontati con questa tabella di elementi attesi.
local expectedItems = populateHashMap(testHashMap, NUM_TEST_ITEMS)
-- Ottenere le pagine può errore. In questo caso, lo lasceremo errore e interromperemo l'esecuzione del programma,
-- ma potresti volerlo chiamare e gestirlo in modo diverso.
print(`Getting HashMap pages with ListItemsAsync...`)
local pages = testHashMap:ListItemsAsync(NUM_TEST_ITEMS)
local retrievedItems = getItemsFromAllPages(pages)
local numMatchingItems = compareAllItems(retrievedItems, expectedItems)
-- Se non ci fossero errori nella impostazione o nel ricevere gli oggetti, tutti gli oggetti dovrebbero corrispondere.
print(`Program complete. {numMatchingItems}/{NUM_TEST_ITEMS} retrieved items matched the expected values.`)

RemoveAsync

()
Resa

Rimuove un oggetto dalla mappa hash.

Parametri

key: string

La chiave da Rimuovere.

Valore predefinito: ""

Restituzioni

()

Campioni di codice

Removing data from a MemoryStore Hash Map

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

Resa

Imposta il valore di una chiave nella mappa hash, sostituendo qualsiasi valore esistente.

Parametri

key: string

La chiave il cui valore è da Impostare.

Valore predefinito: ""
value: Variant

Il valore da Impostare.

Valore predefinito: ""
expiration: number

Scadenza dell'oggetto in secondi, dopo cui l'oggetto viene automaticamente rimosso dalla mappa hash.Il tempo massimo di scadenza è di 45 giorni (3.888.000 secondi).

Valore predefinito: ""

Restituzioni

Campioni di codice

Aggiungere dati a una mappa Hash di MemoryStore

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

Variant
Resa

Recupera il valore di una chiave da una mappa hash e ti consente di aggiornarla a un nuovo valore.

Questo metodo accetta una funzione di richiamo che recupera il valore chiave esistente e lo passa a una funzione di trasformazione, che restituisce il nuovo valore per l'Articolo, con queste eccezioni:

  • Se la chiave non esiste, il vecchio valore passato alla funzione è nil .
  • Se la funzione restituisce nil , l'aggiornamento viene annullato.

Il nuovo valore viene salvato solo se la chiave non è stata aggiornata (ad esempio, da un diverso Serverdi gioco) dal momento in cui è stata letta.Se il valore cambia in quel momento, la funzione di trasformazione viene nuovamente chiamata con il valore dell'elemento più recente.Questo ciclo si ripete fino a quando il valore viene salvato con successo o la funzione di trasformazione restituisce nil per annullare l'operazione.

Parametri

key: string

La chiave il cui valore vuoi Aggiornarmento.

Valore predefinito: ""
transformFunction: function

La funzione di trasformazione, che Fornire. Questa funzione prende il vecchio valore come input e restituisce il nuovo valore.

Valore predefinito: ""
expiration: number

Scadenza dell'oggetto in secondi, dopo cui l'oggetto viene automaticamente rimosso dalla mappa hash.Il tempo massimo di scadenza è di 45 giorni (3.888.000 secondi).

Valore predefinito: ""

Restituzioni

Variant

L'ultimo valore restituito dalla funzione di trasformazione.

Campioni di codice

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.

Updating a Memory Store Hash Map

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)

Eventi