Deleting indexes from a dictionary

How can I automatically delete an index from a dictionary after a countdown but reset that countdown if that index is modified? To automatically delete the index, I know there’s task.delay (see the code below), but I don’t know how to reset the countdown with this method.

This is also for a ModuleScript.

local dictionary = {
  ["A"] = 100
}

function dictionary:addIndex(index, value)
  self[index] = value

  task.delay(3, function()
    self[index] = nil
  end)
end

return dictionary

You should provide a method called something like setIndex which handles resetting the countdown. task.delay returns a thread which you can store in a second dictionary and close the thread to cancel the countdown. You might be able to do this with no threads at all, also. If you have a method called getIndex, you can compare the current time to a “lastUpdated” time and return nil if the entry is expired. If you have a lot of entries this will save you from starting a lot of threads which could be slightly faster.

You could check if the Index is not the same as last time and cancel it from a list.

local Dictionary = {}
local Threads = {}

local function DelayRemove(Index) -- Pre-Defined Function for Consistency
	Dictionary[Index] = nil
end

function Dictionary.AddIndex(Index, Value)
	if Dictionary[Index] and Dictionary[Index] ~= Value then
		task.cancel(Threads[Index])
	end
	
	Dictionary[Index] = Value
	Threads[Index] = task.delay(3, DelayRemove, Index)
end

return Dictionary

The dictionary I’m making stores the time from workspace:GetServerTimeNow() for each entry, so would it be reasonable to have an infinite while loop go through all of the entries and delete any that are too old?

Theres no need to check it in a loop since you can have that check be in the “get” function. To the caller observing the dictionary theres no difference between, it being actively deleted at the exact specified time, or it being unavailable/nil anytime after the expiration time.

Alright, thank you, everyone. I’ve decided to just create and cancel a new thread whenever the index is changed. The dictionary isn’t ridiculously big (I hope it won’t become ridiculously big during gameplay), so speed shouldn’t be a concern.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.