- What does the code do and what are you not satisfied with?
So I’m working on Pet random system and I use this code below for random
local PetsChance = { ['Common'] = 50; local Chance = 0 local ChosenNumber = math.random(1,100) for i, v in pairs(PetsChance) do Chance = Chance + v if ChosenNumber <= Chance then -- Pet Choose end end
But the issue of this method is the table wasn’t sort by order it’s written in so I fixed it by
adding a new Table and put everything inside PetsTable to the new one and It’s working but I’m wondering If there is a better way of inserting info to new table everytime function called.
local SortArray = {}
function Pets:ChoosePet(Rarity)
for _, Info in pairs(self[Rarity.."Egg_Rate"]) do
table.insert(SortArray, Info)
end
table.sort(SortArray, function(a,b)
return a.Chance < b.Chance
end)
- How (specifically) do you want to improve the code?
Is there anyway to chance the actual PetsTable sort order instead of sorting new table everytime function called.
Here is a full modulescript
local Pets = {}
local Pets_Folder = game.ReplicatedStorage:WaitForChild("Pets")
local CommonPets_Folder = Pets_Folder:WaitForChild("CommonPets")
local UncommonPets_Folder = Pets_Folder:WaitForChild("UncommonPets")
Pets.CommonPets = {
["Legendary"] = {
CommonPets_Folder:WaitForChild("Bull")
};
["Rare"] = {
CommonPets_Folder:WaitForChild("Fox")
};
["Uncommon"] = {
CommonPets_Folder:WaitForChild("Bunny");
};
["Common"] = {
CommonPets_Folder:WaitForChild("Dog");
CommonPets_Folder:WaitForChild("Cat");
};
}
Pets.UncommonPets = {
["Legendary"] = {
UncommonPets_Folder:WaitForChild("Wyvern")
};
["Rare"] = {
UncommonPets_Folder:WaitForChild("Omega Bull")
};
["Uncommon"] = {
UncommonPets_Folder:WaitForChild("Deer");
UncommonPets_Folder:WaitForChild("Kitty");
};
["Common"] = {
UncommonPets_Folder:WaitForChild("Doggy");
UncommonPets_Folder:WaitForChild("Foxy");
};
}
Pets.CommonEgg_Rate = {
['Legendary'] = {
Chance = 4,
Name = 'Legendary'
};
['Rare'] = {
Chance = 10,
Name = 'Rare'
};
['Uncommon'] = {
Chance = 35,
Name = 'Uncommon'
};
['Common'] = {
Chance = 51,
Name = 'Common'
};
}
local SortArray = {}
function Pets:ChoosePet(Rarity)
for _, Info in pairs(self[Rarity.."Egg_Rate"]) do
table.insert(SortArray, Info)
end
table.sort(SortArray, function(a,b)
return a.Chance < b.Chance
end)
local ChosenNumber = math.random(1,100)
local Chance = 0
for _, InfoTable in pairs(SortArray) do
Chance = Chance + InfoTable.Chance
if ChosenNumber <= Chance then
local ChosenPet = self[Rarity.."Pets"][InfoTable.Name][math.random(1,#self[Rarity.."Pets"][InfoTable.Name])]
if ChosenPet then print(ChosenPet.Name) end
SortArray = {}
return ChosenPet
end
end
end
Looking good?
- Good
- Not Bad
- Bad
0 voters