Advice and tips on saving a table

I’m currently working on an inventory system using Datastore2, so please ignore the dirty lines of code and whatnot, this is my first week on this! :slight_smile: . My code works and I don’t have any issues with my current script, but I feel like this is an unsafe way to do an inventory store with Datastore2, so any tips or advice would be helpful. The only question I have is that should I create an inventory in a module script instead?

Thanks

Script


DataStore2.Combine("Data1", "Inventory")

local players = game:GetService("Players")
local replicatedStorage = game:GetService("ReplicatedStorage")
local serverScriptService = game:GetService("ServerScriptService")


local part = workspace.Part
local remoteEvent = replicatedStorage:WaitForChild("RemoteEvent")
local petsModule = require(serverScriptService:WaitForChild("ModuleScript"))

local inventory = {}

players.PlayerAdded:Connect(function(player)
	local inventoryData = DataStore2("Inventory", player)
	
	inventory = inventoryData:GetTable(inventory)
	for i, v in pairs(inventory) do
		remoteEvent:FireClient(player, inventory[i].Name)
		print(i, v)
	end
	print(inventory)
	
end)

part.ClickDetector.MouseClick:Connect(function(player)
	local randomPetID = math.random(1, #petsModule)
	local randomPetData = petsModule[randomPetID]
	
	remoteEvent:FireClient(player, randomPetData.Name)
	table.insert(inventory, randomPetData)
end)

players.PlayerRemoving:Connect(function(player)
	local inventoryData = DataStore2("Inventory", player)
	inventoryData:Set(inventory)
end)

Localscript


local remoteEvent = replicatedStorage:WaitForChild("RemoteEvent")

local scrollingFrame = script.Parent.ScrollingFrame

remoteEvent.OnClientEvent:Connect(function(petName)
	
	local newTextButton = Instance.new("TextButton")
	newTextButton.Parent = scrollingFrame
	newTextButton.Name = "TextButton"
	newTextButton.Text = petName
	
end)

Sorry for the useless comment but what’s datastore2?

How to use DataStore2 - Data Store caching and data loss prevention

This link will explain it better than I will