Please note, that I'm not into arguing as there's nothing wrong with what I'd like to comment
Arbitrary order one gets from pairs may not be acceptable to get the sequence of lines of text, true.
But when you have to delete things from a table while still traversing it - the pairs lets you write an easier implementation.
Look at this sample with pairs:
Code: Select all
for k,v in pairs(some_table) do
if v.dead then
some_table[k] = nil
end
end
Code: Select all
for k,v in ipairs(some_table) do
if v.dead then
table.remove(some_table, k)
end
end
Now I'll move on to execution time (i.e. the speed).
The pairs iterator isn't always slower that ipairs.
Some guy at Garry'sMod forums have posted this: https://facepunch.com/showthread.php?t=875909
Also here are some benchmarks posted @lua-users: http://lua-users.org/lists/lua-l/2009-11/msg01007.html
Here's my own measurements too:
Actual code:
Code: Select all
local t = {}
for i=1,10000 do
t[i] = math.random(1,1000000)
end
local time = os.clock()
for k,v in pairs(t) do
end
print(os.clock()-time)
local time = os.clock()
for k,v in ipairs(t) do
end
print(os.clock()-time)
Code: Select all
Lua 5.2
pairs: 0.000897
ipairs: 0.000666
LuaJIT
pairs: 0.000117
ipairs: 0.000068
Love2d with LuaJIT:
pairs: 0.000045
ipairs: 0.000035
Code: Select all
local t = {}
for i=1,10000 do t[i] = math.random(1,1000000) end
local time = os.clock()
for k,v in pairs(t) do
end
print(os.clock()-time)
local time = os.clock()
for k,v in ipairs(t) do
end
print(os.clock()-time)
The results would be different:
Code: Select all
Lua 5.2
pairs: 0.001395
ipairs: 0.001443
LuaJIT
pairs: 0.00016
ipairs: 0.000094
Love2d with LuaJIT
pairs: 0.000044
ipairs: 0.000028
But I'd say it all depends on what Lua implementation one is working with, how it is integrated into a framework and what coding-style habbits one exerts.
The numbers can't lie