How to make damage apply to the oldest shield

I’m making a custom health system and one of its functions is a value called shield health which takes damage before the players regular health when its above 0.

My problem is that I don’t know how to differentiate different shields. My best guess is to use a table, and every time a new shield is added it gets put in the table, and all the shields combined determine the shield health, and when damage is taken it subtracts from the oldest shield in the table, but I’m not very experienced with tables so I don’t know how to do this.

1 Like

Why do you want multiple shields?

1 Like

It’s just how I want the system to work. If 2 different abilities that give a shield are applied, I’d want them to stack and have the older shield to take priority over damage, or I guess more specifically the shield with the shortest remaining duration

Here are my thoughts and code prototype for the instructions you described, not tested yet but just showcases how it can be done:

--Choose an array to hold shield data
--Good as indexes hold information for which shield was last added
local shield = {}

table.insert(shield, {"ShieldType1", 50})

table.insert(shield, {"ShieldType2", 50})

table.insert(shield, {"ShieldType1", 50})
--Dictionary containing total shield
--Dictionary is good for totals of a shield type but doesn't contain indexes which is the information of the last shield added
--If you dont want shield types just sum the array
local totalShieldHealth = {}

--Convert array into dictionary
for i, v in pairs(shield ) do
shieldType = v[1]
shieldAmount = v[2]
if totalShieldHealth[shieldType] then
totalShieldHealth[shieldType] += shieldAmount 
else
totalShieldHealth[shieldType] = shieldAmount 
end


end
--Oldest is in the first array
local lastShieldDataInstance = shield[1]

local oldestShieldInstanceType = lastShieldDataInstance[1]
local oldestShieldInstanceAmount = lastShieldDataInstance[2]

local newShieldHealth = oldestShieldInstanceAmount  - damage

if newShieldHealth <= 0 then
table.remove(lastShieldDataInstance , 1)

remainderDamage = math.abs(newShieldHealth) --Do something which remainder damage, up to you
end

For more advanced you will notice table.remove is not efficient as it has to move down all the indexes and minus them by one. I would consider a datastructure perhaps something like a linked list where you can pop off the oldest instance.

1 Like