This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Mackan90096's profile picture

[Question] for i, v in ipairs(gems) do ?

Started by Mackan90096, 13 May 2013 - 04:37 AM
Mackan90096 #1
Posted 13 May 2013 - 06:37 AM
Hi! I'm wondering what these do:


for i, v in ipairs(gems) do

What do they do?
Please explain as detailed as you can as I'm not the best at English..

Thanks in advance //Mackan90096
theoriginalbit #2
Posted 13 May 2013 - 06:44 AM
1) You could have asked me in the other thread where I gave you code with it, you don't need to go make a new topic for each question you have if its even remotely to do with the topic at hand
2) Do you ever Google? Here is an example search: link here is another search link
Mackan90096 #3
Posted 13 May 2013 - 06:45 AM
1) You could have asked me in the other thread where I gave you code with it, you don't need to go make a new topic for each question you have if its even remotely to do with the topic at hand
2) Do you ever Google? Here is an example search: link here is another search link

1) Ok.. Didn't realize that..
2) Yes, I do use Google, I just wanted to get a "Good" answer so to say..
theoriginalbit #4
Posted 13 May 2013 - 07:06 AM
2) Yes, I do use Google, I just wanted to get a "Good" answer so to say..
Well say we have this table


local t = {
  12,
  3,
  5,
  hello = 'hello',
  4,
  world = 'world',
  10,
  key = 'something',
}


now if we use a standard incremental for loop like this


for i = 1, #t do
  print(i..' : '..t[i])
end


we get this output
1 : 12
2 : 3
3 : 5
4 : 4
5 : 10

now if we use a generic for loop, pairs



for k,v in pairs(t) do
  print(k..' : '..v)
end

we get this output
1 : 12
2 : 3
3 : 5
4 : 4
5 : 10
key : something
world : world
hello : hello


now if we use a generic for loop, ipairs


for i,v in ipairs(t) do
  print(i..' : '..v)
end

we get this output

1 : 12
2 : 3
3 : 5
4 : 4
5 : 10

notice how the ipairs is the same as a standard incremental for loop, and can only access indexed values… well you can use either, but using the standard incremental for loop was decided (in a massive discussion months ago) is much more efficient… now as you can also see the pairs loop lets you access indexed pairs as well as key/value pairs…