How could I reduce repetitive datastore variables?

Hey, I am working on a mining game and I have a bunch of repetitive code, would there be a way for me to have a function that takes a string input and sets the variables below based on the string?

For example, if I wanted to add a new data store named Diamonds, I could just run a function to create the diamondStore datastore

I am using DataStore2

-- Repetitive Code
	local coalStore = DataStore2("coal", player)
	local coal = Instance.new("IntValue")
	coal.Name = "Coal"
	coal.Value = coalStore:Get(0)
	coal.Parent = leaderstats
	coalStore:OnUpdate(function(newCoal)
		coal.Value = newCoal
	end)
	
	local copperStore = DataStore2("copper", player)
	local copper = Instance.new("IntValue")
	copper.Name = "Copper"
	copper.Value = copperStore:Get(0)
	copper.Parent = leaderstats
	copperStore:OnUpdate(function(newCopper)
		copper.Value = newCopper
	end)

Here is some improved code:

local repetitivestores = {
	"Coal",
	"Copper"
}
--
for i,v in pairs(repetitivestores) do
	local store = DataStore2(string.lower(v), player)
	local value = Instance.new("IntValue")
	local connection = nil
	--
	value.Name = v
	value.Value = store:Get(0) or 0 --incase it is nil? never used datastore2
	value.Parent = leaderstats
	--
	connection = store:OnUpdate(function(newvalue)
		if value.Parent then
			value.Value = newvalue
		else
			connection:Disconnect()
		end
	end)
end
1 Like