# Somebody explain me how the for loop's in pairs and in ipairs work

I just don’t seem to get what “in pairs” and “in ipairs” do and how they work in for loop.
Can somebody explain these terms to me?

Basically, pairs just returns the key and value in a table. You’d use it for looping like if you had a table:
[lua]
local myTable = {};
myTable.x = 1;
myTable.y = 2;
myTable.z = 3;

– k and v are variables. k = key, v = value.
for k, v in pairs(myTable) do
print(k…" => "…v)
end
[/lua]

This would output like:
x => 1
y => 2
z => 3.

Using ipairs is the same, but it has the values in order by their key, meaning the key has to be numeric.

Gimme an example.

[lua]
local ta = {
“a”;
“b”;
[“b”] = “c”;
“d”;

}

for k, v in ipairs(ta) do
print(k, v)
end
[/lua]

This will only print:
1 a
2 b
3 d

ipairs takes a little longer to run, so don’t do it unless it’s important that things are in a specific order.

ipairs is actually faster for numeric tables

No it’s not

It is for tables of up to around a few hundred numerically ordered elements

Someone proved it ages ago but I can’t seem to find the thread again now

(the difference is so small that it basically doesn’t matter)

I just did a test and well I’ll be damned (albeit all my indexes are numerical) ipairs is faster.

I had based my assumption on this.

[editline]2nd June 2013[/editline]

It is, however, several times slower when there are also alphanumeric indexes

From what I remember about the benchmarking, ipairs is faster but the difference is so small that it will never ever matter.

pairs and ipairs are both ordered (yes, pairs orders non-numeric keys by insertion order) but ipairs skips non-numeric keys. That’s about it. I’ve only seen one use of ipairs with the new luajit.

ipairs will also stop when it reaches a hole in the table:

[lua]t = { 1, 2, 3, 4, 5 }
t[ 4 ] = nil

for k, v in ipairs( t ) do
print( k, v )
end[/lua]

``````
1	1
2	2
3	3

``````

So it is only really meant for use on numeric keyed tables that do not have any gaps.

This isn’t true. pairs uses the next function internally which doesn’t specify traversal order. I ran this on the Lua demo site:
[lua]local t = {}

for i=1, 20 do
t[tostring(i)] = i
end

for k, v in pairs(t) do
print(k, v)
end[/lua]

This was the output:

``````
5	5
16	16
15	15
14	14
9	9
8	8
20	20
19	19
12	12
13	13
10	10
11	11
18	18
17	17
4	4
7	7
1	1
6	6
3	3
2	2

``````

I ran the same thing on my Lua 5.2 install on my linux machine and got this:

``````
10	10
11	11
12	12
2	2
5	5
4	4
7	7
6	6
9	9
8	8
20	20
19	19
18	18
17	17
16	16
15	15
14	14
13	13
1	1
3	3

``````