I, v in pairs not reading in order

  1. What do I want to achieve? I am trying to scan through a table in order from first to last.

  2. What is the issue? Instead, it scans in a random order.

  3. What solutions have you tried so far? Checked everywhere but couldn’t find a solution.

Example:

tableExample = {A = "1", B = "2", C = "3"}

for i,v in pairs(tableExample) do
      print(v)
end

Expected:

1
2
3

Recieved:

3
1
2

Please help!

1 Like

Internally, key-value pair tables in Lua/Luau (that aren’t ordered number keys) are represented with a hash map, and therefore do not have any defined order. The order you use to declare your table in your source code has no effect on how the data will actually be laid out in memory. If you need order, use arrays.

1 Like

Thank you! I’ll try using arrays.

It might actually be that the table is mixed. Unless the hashes are completely random, the keys should be converted in a way such that they are numerically ordered. Please point out if I have reached a wrong conclusion.

Arrays seemed to solve the issue, thank you.

No; the hash function is not based on the alphabetical order.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.