What does "for i, v in ipairs do" mean?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
LaserGuns
Prole
Posts: 33
Joined: Sun Apr 29, 2012 12:55 am

What does "for i, v in ipairs do" mean?

Post by LaserGuns »

I don't think that's exactly how its used, but I see "for blah blah in ipairs do" in a lot of code and I think it would be useful.
What does the for/do loop do?
What are ipairs? How do they work?
User avatar
Roland_Yonaba
Inner party member
Posts: 1563
Joined: Tue Jun 21, 2011 6:08 pm
Location: Ouagadougou (Burkina Faso)
Contact:

Re: What does "for i, v in ipairs do" mean?

Post by Roland_Yonaba »

Sometimes, for some reasons, you need to loop trhough a collection of elements.
For loop is meant for that purpose.

Code: Select all

t = { 'a','b','c','d'}
for i = 1, #t do 
   print(i,t[i])
end
will output
1, 'a'
2, 'b'
3, 'c'
4, 'd'
pairs/ipairs are iterators.
They offers better support to loop trough a table.

Code: Select all

t = { 'a','b','c','d'}
for key,value in ipairs(t) do 
   print(key,value)
end
will have the same output as before.
Pairs will also act the same way, and have the same output.

Sometimes, values are not indexed with numeric keys, in a table.
In this case, ipairs won't work, but pairs will.

Code: Select all

t = {}
t.x = 1
t.y = 2
t.z = 3
for key,value in pairs(t) do 
   print(key,value)
end
will output
"x",1
"y",2
"z",3
That's a basic example. You will find more intel here :
Lua_Tables_Tutorial
Pairs/ipairs

There's an online interpreter for Lua here, you can try some snippets there to understand.
Last edited by Roland_Yonaba on Sun Aug 19, 2012 1:45 am, edited 2 times in total.
LaserGuns
Prole
Posts: 33
Joined: Sun Apr 29, 2012 12:55 am

Re: What does "for i, v in ipairs do" mean?

Post by LaserGuns »

Alright. Thanks!
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 5 guests