user7561414
user7561414

Reputation: 9

why lua kv pairs is sequence when key is table

local a = {d = 1}
local b = {d = 2}
local test = {}

test[b] = true
test[a] = true

newtest = {
  d = 1,
  c = 2
}
for i in ipairs(test) do
  print(i.d)
end

for k, v in pairs(newtest) do
  print(k, v)
end

**so why the print of test is in order but the newtest is not every time?

Upvotes: 0

Views: 1023

Answers (1)

Piglet
Piglet

Reputation: 28964

From the Lua 5.3 Reference Manual 6.1 Basic Functions: ipairs

ipairs (t) Returns three values (an iterator function, the table t, and 0) so that the construction

for i,v in ipairs(t) do body end

will iterate over the key–value pairs (1,t[1]), (2,t[2]), ..., up to the first nil value.

So ipairs won't work for test as test is not a sequence starting at index 1. It only has two keys which are tables.

Upvotes: 2

Related Questions