What's wrong with my code?

To add context to this topic, I’m making a “campaign” system (levels) like this

I believe my code has one small mistake that prevents it from saving a level.

What I expect to happen:
-# Selected Level is set to levelData[“NextLevel”]
-# Current Level is set to levelData[“NextLevel”]
-# map.Name is inserted to data.OwnedLevels
What REALLY happens:
-# Selected Level is set to levelData[“NextLevel”], yet it does not save.
-# Current Level is set to levelData[“NextLevel”], yet it does not save.
-# map.Name is NOT inserted to data.OwnedLevels

ServerStorage.Bricks.Bindables.LevelData.Event:Connect(function(win, map, findLevelData, data)
	local levelData = require(findLevelData)
	if levelData.ItemAwardType == "Money" then
	elseif levelData.ItemAwardType == "SubtleItem" then
		if not table.find(data["SubtleItems"], levelData[levelData.ItemAward]) then
			table.insert(data["SubtleItems"], levelData[levelData.ItemAward])
		end
	else
		if not table.find(data["OwnedPackets"], levelData[levelData.ItemAward]) then
			table.insert(data["OwnedPackets"], levelData[levelData.ItemAward])
		else
		end
	end

	if not table.find(data.OwnedLevels, map.Name) then
		table.insert(data.OwnedLevels, map.Name)
		if levelData["ChangeAmount"] then
			data["AmountPackets"] = levelData["ChangeAmount"]
		end
	end

	if levelData["NextLevel"] then
		print("NextLevel:", levelData["NextLevel"])
		print("Before: CurrentLevel:", data["CurrentLevel"], "SelectedLevel:", data["SelectedLevel"])
		data["CurrentLevel"] = levelData["NextLevel"]
		data["SelectedLevel"] = levelData["NextLevel"]
		print("After: CurrentLevel:", data["CurrentLevel"], "SelectedLevel:", data["SelectedLevel"])
	end
end)

^ the code that sets their respective levels

local module = {
	["ItemAwardType"] = "Tower",  -- Tower, Money, Item
	["ItemAward"] = "Betty Bloxxer",
	["Betty Bloxxer"] = {
		["Name"] = "Betty Bloxxer",
		["Price"] = 100,
		["Image"] = "rbxassetid://2748039495"
	},
	["ChangeAmount"] = 2,
	["TIXAmount"] = 25,
	["TIXProduce"] = 10,
	["NextLevel"] = "Baseplate 0-2"
}

return module

^ level data module

local function SaveData(player)
	local playerData = data[player.UserId]
	if playerData then
		local success = false
		local result = nil
		local attempt = 1

		repeat
			success, result = pcall(function()
				return database:UpdateAsync(player.UserId, function(old)
					return playerData
				end)
			end)

			attempt += 1
			if not success then
				warn("SaveData error:", result)
				task.wait(1)
			end

		until success or attempt > 3

		if success then
			print("Selected: " .. (playerData.SelectedLevel or "nil"))
			print("Current: " .. (playerData.CurrentLevel or "nil"))
			for _, level in playerData.OwnedLevels do
				print("Level: " .. tostring(level))
			end
		else
			warn("Failed to save data for", player.Name)
		end
	else
		warn("No data to save for userId", player.UserId)
	end
end

^ saving data

local function LoadData(player)
	local success = false
	local playerData = nil
	local attempt = 1

	repeat
		success, playerData = pcall(function()
			return database:GetAsync(player.UserId)
		end)

		attempt += 1
		if not success then
			warn("LoadData error:", playerData)
			task.wait(1)
		end

	until success or attempt > 3

	if success then
		if not playerData then
			playerData = {
				["SelectedLevel"] = "Baseplate 0-1",
				["CurrentLevel"] = "Baseplate 0-1",
				["OwnedLevels"] = {},
				["PlayerAmount"] = 1,

				["TIX"] = 0,
				["BUX"] = 0,

				["AmountPackets"] = 1,
				["OwnedPackets"] = {
					["Deffy Bloxxer"] = {
						["Name"] = "Deffy Bloxxer",
						["Price"] = 100,
						["Image"] = "rbxassetid://2748040041"
					},
				},

				["AccessoriesWorn"] = {},
				["AccessoriesOwned"] = {},

				["Settings"] = {
					["WorseAnimations"] = false,
				},

				["SubtleItems"] = {},
				["ItemsBought"] = {},
				["RedeemedCodes"] = {},
			}
		end

		local function CheckTower(name, price, image)
			local tower = playerData.OwnedPackets[name]
			if tower then
				tower.Name = name
				tower.Price = price
				tower.Image = image
			else
				warn(name .. " not found") -- Changed from tower.Name to name
			end
		end

		data[player.UserId] = playerData
	else
		player:Kick("DataStore loading failed after retries. Please rejoin.")
	end
end

^ load data
image
^ setting their respective levels’ output
image
^ save data’s output

4 Likes

So this is the solution to the post because I haven’t given a good look but usually people when they are showing code on the dev forum they put them inbetween these ``` one at the start and one at the end, on PC there is a button when writing text there the lgo should be </>.

Do you want me to format the code?

1 Like

Yeah it will make it easy to debug, thanks in advance.

1 Like

I updated the topic, let me know if Loading Data was needed.

Yes. That might help very much.

1 Like

I have updated the topic again.

I may need to see the code where Bindable Event is called, and when is loading & saving data is called.

Players.PlayerRemoving:Connect(function(player)
	SaveData(player)
	data[player.UserId] = nil
end)
game:BindToClose(function()
	if not RunService:IsStudio() then
		for _, player in Players:GetPlayers() do
			task.spawn(function()
				SaveData(player)
			end)
		end
	end
end)

^ save data stuff

Players.PlayerAdded:Connect(LoadData)

^ load data stuff

local function GameOver(win)
	workspace.Enemies:ClearAllChildren()
	workspace.Towers:ClearAllChildren()
	Map.WorldMusic:Stop()
	ServerScriptService.TIXResources.Disabled = true
	
	if win then
		local map = workspace.Map:FindFirstChildOfClass("Folder")
		for _, plr in pairs(Players:GetPlayers()) do
			local data = DataLoad(plr)
			local findLevelData = ReplicatedStorage.Stats.Levels:FindFirstChild(map.Name)
			
			if findLevelData then
				ServerStorage.Bricks.Bindables.LevelData:Fire(true, map, findLevelData, data)
			else
				warn("No level data")
			end
		end
	end
end

^ where the bindable event is fired

Tables passed as arguments via BindableEvents are copied, not direct references. You’re updating a copy of the player’s data. You should store the player’s data where it would be directly accessible to any/all scripts that may modify or read it (ModuleScript!)

3 Likes

Thank you so much! I’ve been stuck on this for a month.

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