my question is why the key&value(512) in tables tt is not same:
i have same lua code:
t={501,502,503,504,505,506,507,508,509,510,511,512}
tt={}
for _, id in pairs(t) do
print(id)
tt[id] = id
end
print("----------------------")
for k,v in pairs(tt) do
print(k,v)
end
As Ivo has pointed out, you should never ever rely on a deterministic order of hash table traversal.
This is extremely prone to breakage (1) across interpreters and (2) across different Lua versions which may affect the implementation details of the hash function.
Additionally, the order of the hash part in practice often depends on the order of insertion - that is, two tables may have the same keys, but need not be iterated in the same order by pairs
/next
due to another sequence of insertion/deletion operations:
> t = {}; t[42] = 1; t[33] = 1; t[101] = 1; for k, v in pairs(t) do print(k, v) end
42 1
101 1
33 1
> t = {}; t[33] = 1; t[42] = 1; t[101] = 1; for k, v in pairs(t) do print(k, v) end
33 1
101 1
42 1
To (reluctantly) answer your question:
Is the order of access to hashkeys in tables different between lua5.1 and lua5.3?
Yes. To ensure that programmers do not rely on the order of traversal, many languages (such as Go) randomize it. Lua 5.2.1 introduced randomization of seeds for hashing. This means that now you can't even rely on order of traversal across program runs. The advantage is that malicious actors can't rely on a certain key having a certain hash (and thus a certain order of traversal given a certain order of insertion of keys) either, making it harder for them to exploit it to e.g. create hash collisions to compromise the availability of a service written in Lua (denial of service).
That said, let me repeat: you should write your code to not rely on the order of traversal due to all the points mentioned above.