-1

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

in lua5.1: enter image description here

in lua5.3: enter image description here

zpx
  • 15
  • 4
  • Does this answer your question? [Why does the same lua script have inconsistent execution results?](https://stackoverflow.com/questions/73741252/why-does-the-same-lua-script-have-inconsistent-execution-results) – shingo Oct 20 '22 at 09:24
  • this question could have been avoided by referring to the manual. also there is absolutely no reason to share a few numbers as a screenshot. – Piglet Oct 20 '22 at 10:04

2 Answers2

2

pairs gives no guarantee in which order the elements of the table are iterated over.

from the documentation on https://www.lua.org/pil/7.3.html:

The pairs function [...] in an arbitrary order.

Ivo
  • 18,659
  • 2
  • 23
  • 35
2

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.

Luatic
  • 8,513
  • 2
  • 13
  • 34