StatsFactory | Stats Calculation

StatsFactory is a module script that centralizes and automates Stats calculation, allowing ordered calculation pipeline, categorization within a stat, dynamic formula, and precise removal.

Get it here: StatsFactory - Creator Store

local StatsFactory = require(path to StatsFactory)

-- you need to define everything here
local Template = StatsFactory.new({
	MaxHealth = 100,
	MaxMana = 50,
	Strength = 1,
	BodyWeight = 0,
}, {
	Health = 100,
	Mana = 50,
	Gold =  200
}, {
	"Bonus",
	"Special",
}, {
	"Flat",
	"Percentage",
	"FlatAfterPercentage"
})

Template.StatsAdded:Connect(function(Stats)
	local Modifier = Stats:Add(30, "Flat", "MaxMana", "Bonus")
	
	Stats:Assign("Mana", Stats:GetStat("MaxMana"))
	
	Stats:Remove(Modifier)
	Stats:Assign("Mana", Stats:GetStat("MaxMana"))
	-- etc
end)

local Guy = Template:new()
Guy.StatChanged:Connect(function(Stat)
	local Value = Guy:GetStat(Stat) -- get the final value of Stat
	print(Value)
end)

Guy.ResourceChanged:Connect(function(Resource)
	local Value = Guy:GetResource(Resource) -- get the final value of Resource
	print(Value)
end)

local SetModifier = Guy:Set(500, "Flat", "Strength", "Special", 0)

local MaxModifierA = Guy:Max(100, "Flat", "Strength", "Special", 0) -- overides SetModifier
local MaxModifierB = Guy:Max(200, "Flat", "Strength", "Special", 1) -- overides MaxModifierA because priorty is 1 > 0
local MinModifier = Guy:Min(300, "Flat", "Strength", "Special", 0) -- min always overides max regardless of priorty if a conflict occured

-- most operations can take in a formula
-- free feel to form a dependency chain, as long as it's not cyclic it will work correctly
local DynamicModifier = Guy:Add(function(PercentageBonusStrength, FlatSpecialMaxHealth)
	return PercentageBonusStrength * 2 + FlatSpecialMaxHealth -- custom formula
end, "Percentage", "BodyWeight", "Bonus", {"Percentage", "Flat"}, {"Strength", "MaxHealth"}, {"Bonus", "Special"})

Guy:Remove(DynamicModifier)

Guy:Gain("Gold", 55) -- resource is separate from regular stat calculation, cannot be referenced via dynamic modifier, or be used with Add/Set/Min/Max, only Gain and Assign

-- deep clone Guy, but won't inherit connections
local Guy2 = Guy:Clone()

-- does not return a modifier, cannot take in a formula, light-weight version of Add
Guy2:Increment(20, "FlatAfterPercentage", "MaxHealth", "Bonus")

-- Destroy when no longer needed
Guy2:Destroy()
2 Likes