Why "pairs" working randomly in lua? How to fix it?
Why next code:
local x = {X=1, Y=2, Z=3}
local y = {}
for Key, _ in pairs(x) do
table.insert(y, Key)
end
for i, v in ipairs(y) do
print(i, v)
end
Why when we run it, it always returning random result?
1 Z
2 Y
3 X
Or
1 Y
2 X
3 Z
Solution 1:
This is by design to reduce the risk of hashing attacks. You can store the keys, sort them, and then iterate over that table with keys if you need a specific/fixed order. Also see this SO answer for a related discussion.