Search code examples
luaiteratorlua-table

Is there a way to tell `next` to start at specific key?


My understanding is that pairs(t) simply returns next, t, nil.

If I change that to next, t, someKey (where someKey is a valid key in my table) will next start at/after that key?

I tried this on the Lua Demo page:

t = { foo = "foo", bar = "bar", goo = "goo" }

for k,v in next, t, t.bar do
  print(k);
end

And got varying results each time I ran the code. So specifying a starting key has an effect, unfortunately the effect seems somewhat random. Any suggestions?


Solution

  • Every time you run a program that traverses a Lua table the order will be different because Lua internally uses a random salt in hash tables.

    This was introduced in Lua 5.2. See luai_makeseed.