Table sorts randomly

Hello, I’m trying to make a pet system. But the pets in the chest doesn’t sort in the right order. I’ve even tried to use table.sort() but it didn’t seemed to work.

Here’s the pet list

contains = {
            pet_type_1 = 5,
            pet_type_2 = 15,
            pet_type_3 = 30,
            pet_type_4 = 50,
        }

Here’s the selecting script:


function getRandomPet(chestStr)
	local chest = Chests[chestStr]
	local generateChance = math.random(0,1000000) / 10000
	local counter = 0
	local petSelected = nil
	generateChance = 75
	table.sort(chest["contains"])
	for pet, chance in pairs(chest["contains"]) do
		print(pet)
	end
end

printing the pet gives these values in order.

pet_type_1
pet_type_4
pet_type_2
pet_type_3

Removing the table.sort doesn’t fix anything.
Can someone please tell why are those listed randomly?

Since pairs has the same behaviour as next. The order of pairs/next is undefined.

From Lua 5.1 Reference Manual

Then what I need to do so they sort normally?

I recommend instead of using string keys like pet_type_1, pet_type_2, etc, use numeric keys (make it an array for example), and then use ipairs or generalized iteration to iterate the table.

I have tried using ipairs but it didn’t seemed to give me a solution. I made the pets table like that and the issue is fixed:

[1] = {"pet_example_1", 5},