Yeah, that was what I thought at first.
You ought to put an order to it somehow. There are a few ways-
Table for each pet
You change the table to this:
{
{Name = "Bee" ;Rarity = 20};
{Name = "Turkey" ;Rarity = 40};
}
(leaving spaces to align the rarity and moving the ;
doesn’t make it work better, just looks nicer that way)
Now you can use ipairs
or a numeric for
loop or just continue using pairs
to loop over the data. The v
of your "i,v pairs loop
will just be another table, you will need to get v.Name
or v.Rarity
for what you need.
The downside is that there’s a bunch more little quotes and curly braces to write than before.
But this is sort of the right way to do it. You not only get an ordering, but can easily add more properties to the pets, like price, favorite color etc. (unless there’s some other module with that info)
So any examples following this are going to be kind of stupid.
Interleaved name and rarity
local pets = {
"Bee", 20;
"Turkey", 40;
}
for i = 1, #pets, 2 do -- loop over the table, skipping second, fourth, sixth etc. thing
local name = pets[i]
local rarity = pets[i+1]
-- ...
end
Metatable
local pets = setmetatable({}, {__newindex = function(tbl, key, value)
-- whenever pets.%Name% = %Rarity% is done, instead insert {Name = %Name%; Rarity = %Rarity%}
rawset(tbl, #tbl+1, {Name = key, Rarity = value})
end})
pets.Bee = 20
pets.Turkey = 40
-- result is the exact same table as in the first example
This is stupid and 10x slower, but also a way to do it.
“Now I can’t do pets[name]
to get the rarity, what gives?”
Make a new, separate table. Loop over the pets table, and set newPets[name] = rarity
. You now have the same table that you posted and that goes in a random order with pairs, but also a different table (by me) that has an order.