Comparing datastored towers to add a new table

Hello as I’ve been learning datastores I’ve been making a tower defense game and its been going great! but I’ve encountered an issue first hand and it is that when I add a new tower if a player has their data saved before the addition of a tower the person cannot buy this tower. I have tried various ways but did not find a way. Its like comparing two data tables

 ["Towers"] = { --preset towers
		["testtower"] = {
			["Name"] = "scout",
			["Bought"] = false,
			["Equipped"] = false,
			["Slot"] = 0,
		},
               ["testtower2"] = {
			["Name"] = "minigunner",
			["Bought"] = false,
			["Equipped"] = false,
			["Slot"] = 0,
		},

},

 ["Towers"] = { --player towers
		
               ["testtower"] = {
		 	["Name"] = "scout",
			["Bought"] = false,
			["Equipped"] = false,
			["Slot"] = 0,
		},

},

I would also like to say that Im trying to make it add the new tower to the old player towers

I also wont reply for a bit as it is late where i live

So I think I understand what you’re saying.

you use this to check if a tower is already bought or not, but that wont work if they dont have that tower, since its nil. You can instead just check if they have it in the table by doing

if Towers["testtower2"] == nil then --if they dont have the tower

Doing it with the Bought part

if Towers["testtower2"]["Bought"] == nil then

would return an error because “testtower2” == nil

You should remove the Bought info all together and instead check if the tower is nil inside the data table.

Then to add the tower you’d just do

--as an example, DataTowers is the datastore table, Tower is the tower you're trying to buy, so "testtower2"
--Towers is the buyable towers.
DataTowers[Tower] = Towers[Tower]
1 Like

I solutioned this because this would work but the script I listed wasn’t the real script for the game but in my game there is a lot of towers and the issue is then checking if multiple towers are missing without having to manually make sure for every tower which makes the script messy

Why would you need to do this? And can’t you just do a loop to check all the ones that are missing?

yes but I don’t know how to do this, I’ve already tried but it returns a random tower as missing when another tower was missing and the random tower isn’t missing.

for i,v in pairs(DataTowers) do
    if Towers[i] ~= nil then
        print("You own this tower")
    else
        print("You don't own this tower")
    end
end
1 Like

Thank you this finally worked but just for info what does the I in i,v pairs do? I’ve only ever used the v

And how would i add the missing tower to the new data

I is the Index, its what you’ve named the towers, so printing i would give you the name, like “TestTower”, but not anything else.

You would do

Towers[i] = v