MemoryStoreHashMap

사용되지 않는 항목 표시

*이 콘텐츠는 AI(베타)를 사용해 번역되었으며, 오류가 있을 수 있습니다. 이 페이지를 영어로 보려면 여기를 클릭하세요.

만들 수 없음
복제되지 않음

MemoryStoreService 내에서 해시 맵에 액세스를 제공합니다.해시 맵은 문자열 키와 임의의 값이 연결된 아이템의 컬렉션으로, 최대 허용 크기(메모리 저장소 참조)까지입니다.키에는 순서 보장이 없습니다.

요약

메서드

속성

메서드

GetAsync

Variant
생성

해시 맵에서 키의 값을 검색합니다.

매개 변수

key: string

가치를 가져오다키.

기본값: ""

반환

Variant

값 또는 nil 키가 존재하지 않으면 값.

코드 샘플

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
생성

해시 맵의 항목을 열거하기 위한 MemoryStoreHashMapPages 개체를 반환합니다. 유효한 범위는 1에서 200까지입니다.

매개 변수

count: number

반환할 수 있는 최대 아이템 수.

기본값: ""

반환

항목을 MemoryStoreHashMapPages 인스턴스로 열거하는 MemoryStoreHashMapPages 인스턴스입니다.

코드 샘플

The code below lists all the items in a Memory Store Hash Map.

Listing items in a 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("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

()
생성

해시 맵에서 항목을 제거합니다.

매개 변수

key: string

제거할 키.

기본값: ""

반환

()

코드 샘플

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

생성

해시 맵에서 키의 값을 설정하여 기존 값을 덮어씁니다.

매개 변수

key: string

설정할 값이 있는 키.

기본값: ""
value: Variant

설정할 값.

기본값: ""
expiration: number

아이템이 초 후에 만료되어 해시 맵에서 자동으로 제거됩니다.최대 만료 시간은 45일(3,888,000초)입니다.

기본값: ""

반환

코드 샘플

Adding data to 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 setSuccess then
print("Set succeeded!")
else
warn(setError)
end

UpdateAsync

Variant
생성

해시 맵에서 키의 값을 검색하고 새 값으로 업데이트할 수 있게 합니다.

이 메서드는 기존 키 값을 검색하고 변환 함수에 전달하는 콜백 함수를 수락하며, 다음 예외와 함께 아이템에 대한 새 값을 반환합니다.

  • 키가 존재하지 않으면 함수에 전달된 이전 값은 nil입니다.
  • 함수가 nil를 반환하면 업데이트가 취소됩니다.

새 값은 읽은 순간부터 키가 업데이트되지 않았다면(예: 다른 게임 서버에서) 저장됩니다. The new value is saved only if the key was not updated (for example, by a different game server) since the moment it was 읽음.해당 시간에 값이 변경되면 변환 함수가 가장 최근 항목 값으로 다시 호출됩니다.이 주기는 값이 성공적으로 저장될 때까지 반복되거나 변환 함수가 작업을 취소하기 위해 nil를 반환할 때까지 반복됩니다.

매개 변수

key: string

값을 업데이트하려는 키.

기본값: ""
transformFunction: function

제공하는 변환 함수. 이 함수는 입력으로 이전 값을 받아 새 값을 반환합니다.

기본값: ""
expiration: number

아이템이 초 후에 만료되어 해시 맵에서 자동으로 제거됩니다.최대 만료 시간은 45일(3,888,000초)입니다.

기본값: ""

반환

Variant

변환 함수에서 마지막으로 반환된 값.

코드 샘플

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)

이벤트