How do i know if there's no key (Ordered with a number) to load a previous key?

The title might be confusing, but it’s worth to read what i’m talking about. I’m creating a Rollback system for DataStore, the system is like this:

  • Each player has a DataStore, it contains a key with a number, for example, this player have a key with the number 1, 2, 3, 4, 5, 6, and 7.
  • The player has a key in a DataStore which would get the last number used to save the data. For example, in this case would be 7
  • If a Rollback happens, when the player logs in, he will not load the key with the number 7, he will load the key with the number that the Rollback system wants to get, for example, 3.

However, i would like to know if that key doesn’t exist, for example:

  • The player’s last number saved was 8, he got the keys 2,3,7, and 8.
  • The Rollback System would load the key with the number 6

Since there’s no key with the number 6, nothing would load, and to prevent that, i would like to load the the key with the number 3 instead, but i don’t know how to do it. In easier terms:

  • If there’s no key with the number 6, then it would load the previous one saved, which would be 3.

I’m stuck in this part, and i’m struggling with this, thanks for reading, and i hope you help me :slight_smile:.

Well, to solve this you would have to do a presence check on the data.

As you aptly noted, if their is no data in key 6 then nothing would load - so your first step is to recognise that by simply saying something on the lines of:

if not data.key6 then...

From beyond that, you can then cycle through the stores 1 by 1 by simply subtracting 1 off the current number. If you store the request like so:

data = {key1 = "apple", key3 = "banana", key5 = "orange"}

function rollbackKey(keyNumber)
	keyName = "key"..keyNumber
	if data[keyName] then
		-- do stuff with data
		rollbackKey(keyNumber - 1) -- the next one will now be 1 less.

rollbackKey(6) -- assuming 6 is the one they choose which doesn't exist.

You will need to add checks in the event that no data exists beneath.

But that is generally, the easiest way of doing it if you’ve stored it numerically. Your other method would be doing it based on table order.

1 Like