Is there a way to shorten this script?

This is a default datastore leaderstats script.

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("DatastoreKey")

game.Players.PlayerAdded:Connect(function(Player)
	local Leaderstats = Instance.new("Folder", Player)
	Leaderstats.Name = "leaderstats"
	local Cash = Instance.new("IntValue", Leaderstats)
	Cash.Name = "Cash"
	Cash.Value = 0
	local Level = Instance.new("IntValue", Leaderstats)
	Level.Name = "Level"
	Level.Value = 1

	local Data = DataStore:GetAsync(Player.UserId)
	if Data then
		Cash.Value = Data.Cash
		Level.Value = Data.Level
	end
end)

game.Players.PlayerRemoving:Connect(function(Player)
	DataStore:SetAsync(Player.UserId, {
		["Cash"] = Player.leaderstats.Cash.Value;
		["Level"] = Player.leaderstats.Level.Value;
	})
end)

It’s the one i use for most games and most of the times it’s very easy and practical. Though i’m curious if there’s a way to shorten it.

When i want to add a new value for example i have to not only Instance.new() the new value but also add something between these lines:

newValue.Value = Data.newValue
["newValueName"] = Player.leaderstats.newValueName.Value;

It would be very great if i didn’t have to add those two new things when i want a new value or at least one of them, so is there a way to shorten it?

2 Likes

Well I guess technically you could make a function like:

local function newStat(type, name, value, parent)
    local stat = Instance.new(type)
    stat.Name = name
    stat.Value = value
    stat.Parent = parent
end
1 Like

Could make it even smaller by doing:

local function newStat(type, name, value, parent)
    local stat = Instance.new(type,parent)
    stat.Name = name
    stat.Value = value
end
1 Like

Instance.new() with parent argument is strongly not recommended - PSA: Don't use Instance.new() with parent argument

4 Likes