Why does the same lua script have inconsistent execution results?

Viewed 35

Why does the same lua script have inconsistent execution results?

hello.lua

obj = {
    a = 'haha',
    b = 'jiji',
    c = {
        name = 'tom',
        age = 15
    }
}

for i, v in pairs(obj) do
    if (i == 'c') then
        print(i,v.age,v.name)
        break
    end
    print(i, v)
end

Result

Result

Thank you for your answer!!

2 Answers

The documentation is very clear, the order is not specified. See https://www.lua.org/manual/5.4/manual.html#pdf-next

The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numerical order, use a numerical for.)

Lua tables use a hash map for implementing their hash part. The order in which your entries will be iterated by pairs/next depends on the hashes of the keys (in this case, the hashes of the strings "a", "b", "c") and their order of insertion.

First of all, hashing and order of insertion may change across different Lua versions, different interpreters (LuaJIT f.E.), so you should never rely on it being one way or another. You will probably want to either sort a list of table keys before traversal or to use an ordered map.

Second, hashing - and thus order of traversal - varies across program runs as of Lua 5.2, which introduces hash seeding to avoid hash flooding attacks: The interpreter will generate a random seed at runtime to use in the calculation of hashes to make it harder for attackers to force hash collisions (which result in detrimental table performance).

Related