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

for k,v in pairs <> for i,v in ipairs

Started by Engineer, 09 March 2013 - 10:59 PM
Engineer #1
Posted 09 March 2013 - 11:59 PM
Hi,

I was messing around with this loop, for k, v in pairs ( yourTable ) do, and I was wonder what the other loop does.

The other loop is
for i, v in iparis ( yourTabe ) do

I know this:

local tTable = {6,5,4,3,2,1}
for k, v in pairs( tTable ) do
   print(k.. "\t" ..v)
end
--outputs:
1   6
2   5
3   4
4   3
5   2
6   1

But f I use .. in ipars( tTable ) do .. I get the same thing.

What is the difference between those?
Engineer
theoriginalbit #2
Posted 10 March 2013 - 12:01 AM
ipairs is index, value over key, value

so its like doing
for i = 1, #tTable do

pretty sure ipairs has been remove in the new Lua since you can just do whats above.

doing
for i = 1, #tTable do
and doing
for i, v in ipairs(tTable) do
will not work for a table like so

local tTable = {
  someKey = "Some Value"
}

in that case you must use pairs.
AfterLifeLochie #3
Posted 10 March 2013 - 12:45 AM
ipairs() iterates a set of numerically-indexed items in a table. All values from 1 to the first missing number-key will be iterated. Non-numerical items will not be iterated.

pairs() will iterate all key-value pairs, regardless of their indexing, order, if there are numbers missing, or how they are mapped in the table.