Jump to content




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


  • You cannot reply to this topic
2 replies to this topic

#1 Engineer

  • Members
  • 1,378 posts
  • LocationThe Netherlands

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

#2 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

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.

#3 AfterLifeLochie

    Wiki Oracle

  • Moderators
  • 480 posts
  • LocationAfterLifeLochie's "Dungeon", Australia

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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users