How to avoid repeating code using tables and dictionaries?

I want to figure out a way to avoid repeating code whilst using tables/dictionaries.
So basically, here is a code sample:

local Table={
["Type1"]={
   ["Health"]=100,
   ["Armor"]=100,
   ["Damage"]=5
 },
["Type2"]={
   ["Health"]=150,
   ["Armor"]=150,
   ["Damage"]=3
},
}

So if I would to have like 20 types, how would I avoid repeating the same indexes that I have and avoid the copy pasting left and right to have a more dry and neat code?

1 Like

By

do you mean something like this?


Roblox already makes sure you don’t reuse the same index in the same table.


Or do you mean not repeating the “Health”, “Armor” and “Damage” keys?
DRY is for code, this is data. I wouldn’t do anything extra here since that would make it harder to read and understand.

Yes I meant the latter one, copy pasting the same “Health” “Armor” “Damage” keys in this example… I understand what you mean in terms of readability, but this is for convenience in my case. I have way way more indexes and tables within tables. I am wondering if you could do thing in a different way like maybe have a “custom table type?”, if that was a thing that automatically have the first and second…indexes set…Or some other way.

If you really want to you could do something like this

function newWeapon(health, armor, damage)
    return {
        Health = health,
        Armor = armor,
        Damage = damage
    }
end

then do

local Table = {
    Type1 = newWeapon(100, 100, 5),
    Type2 = newWeapon(150, 150, 3)
}

(you don’t need the [""] in this situation btw)

2 Likes

Yea this can def. help my case, thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.