-1

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

1 Answers1

3

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.

Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
  • when using selected answer, getting this error C:\Windows\lua.exe: ml\ml.lua:135: attempt to compare two nil values stack traceback: ml\ml.lua:135: in function [C]: in function 'table.sort' ml\ml.lua:135: in field 'SolveIt' ml\ml.lua:160: in main chunk [C]: in ? –  Jan 14 '22 at 15:02
  • You are not just using the selected answer; you've integrated the selected answer in your code and made a mistake somewhere, as the selected answer works by itself. You'll have to open a new question and provide your code that doesn't work if you want to get help. I suspect your sort function evaluates the wrong attributes (`a.value < b.value`). – Paul Kulchenko Jan 14 '22 at 16:05