• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Lua Iterators pairs and ipairs don't work correctly

Joe Rod

Discord: joerod1
Joined
Mar 16, 2011
Messages
499
Solutions
2
Reaction score
172
GitHub
joerod1
Hi, when i try to iterate a table it does not iterate in order, i.e.:
Code:
testTable =
{
   ["a"] = 2,
   ["b"] = 3,
   ["c"] = 4,
   ["d"] = 5
}
  for i,x in pairs(testTable) do
     print(i.."_"..x)
   end

prints:
Code:
a_2
d_5
c_4
b_3

How can be fixed?
Thanks in advance
 
The order when looping with pairs is undefined.
For this special case this will solve it:
Code:
local t = {nil, "a", "b", "c", "d"}
for k, v in pairs(t) do
print(k .. " _ " .. v);
end
 
The only way to get an ordered outcome is when you use a numeric index just like Santi already said but instead of pairs use
Code:
for x = 1,#t do
because this method is a lot faster then pairs or ipairs
 
Back
Top