for key,val in next, blockRarities do
-- do stuff
end
I always assumed that this would loop through starting with “Normal”, then “Steel” etc. And I’m pretty sure that’s how it has worked before on previous projects.
(EDIT: Apparently not lol)
If I print the Value when looping through, though, this is the output: Ignore the “not” I just printed it out weirdly…
This is strange, so I thought perhaps it was because I was using a next loop, so I tried pairs and got the same result. Can someone explain to me why the code seems to loop through the Dictionary in such a random order? Is there some kind of logic here?? Thanks!
But if that’s the case, why do Tables/Arrays allow looping in order? Surely the Dictionary should then loop through in ascending order of key size/value, or am I confusing myself here?
If we have a table with ascending integer keys that have no gaps (known as an array), a, and an index, 3, we know that the next value of a is a[3 + 1].
If we have a table with something like string keys, we cannot simply increment the previous key to get the next. We, in fact, need to use the built-in next function. The function is used as next(t, lastKey), where t is the table and lastKey is the previous key of the table. The function returns the key and value of the next (with respect to lastKey) pair. The order of the elements that the function returns is undefined, so we cannot guarantee any specific order.
Fundamentally, it makes sense that dictionaries have no order. What should we use to order the following table?
local t = {
[Vector3.new()] = true,
["hi"] = "bar",
[9] = 123,
[game] = "foo",
}
Arrays also have no inherent order in Lua - the difference is that ipairs will traverse the gapless numeric keys starting at 1 in ascending order (pairs does not have this guarantee, even for arrays).