Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I fix this directory bug with a for i, v in pairs loop?

Asked by 4 years ago
AvailableSpots = {
    ["1"] = true;
    ["2"] = true;
    ["3"] = true;

}

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

output

  1
  true
  3
  true
  2
  true

Why does it skip to 3? How would I fix this?

0
This is probably because the pairs function doesn't have a specified key order, if you want a specified key order, convert your table into an array, then use ipairs  https://stackoverflow.com/questions/55108794/what-is-the-difference-of-pairs-vs-ipairs-in-lua theking48989987 2147 — 4y

1 answer

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

The order a table is written in is not preserved unless your keys are numerical. In your case, this shouldn't be a problem, as your string keys can just as easily be numbers:

AvailableSpots = {
    [1] = true;
    [2] = true;
    [3] = true;
}

for i, v in pairs(AvailableSpots) do
    print(i, v)
end
Ad

Answer this question