Jump to content

Big doubt..


Recommended Posts

Posted

When and where should I use 'pairs' or 'ipairs'?

For example:

  
local table = { "hello", "i", "am", "here", "not" } 
for i, tmp in ipairs(table) do 
    outputChatBox(tmp) 
end 

  
local table = { "hello", "i", "am", "here", "not" } 
for i, tmp in pairs(table) do 
    outputChatBox(tmp) 
end 

Will print the same:

'hello

i

am

here

not'

So.. differences?

Thanks

Posted

ipairs is used to go through a table with integer indexes; pairs to go through string indexes.

local t = { "hello", "i", "am" } 
for i, v in ipairs( t ) do 
  print( v ); 
end -- I am 
  
local t = { ["hello"] = "I am", ["hello_again"] = "not here" } 
--local t = { hello = "I am", hello_again = "not here" } is equivalent of the previous line 
for i, v in pairs( t ) do 
  print( v ); 
end -- I am not here 

By the way, you can't use pairs and ipairs to loop through tables with mixed types of indexes.

Posted

ipairs will iterate the table by numeric index order starting from 1 and until next numeric key is not found, like:

table = { "one", "two", "three", four = "four", five = "five", [5] = "five", six = "six" }

ipairs(test) will stop after table[3] because table[4] is nil. and it will not find test[5], because [4] is missing.

and pairs will output everything with any kind of index, be it number, string or MTA element.

Posted

Also I sometimes don't understand this, I saw many people use ipairs and with your example I think pairs is the best way.

What is the reason?

Posted

ipairs is basically used where order is needed,

while pairs iterates tru table completely random, thus making it a good random generator too.

  • Discord Moderators
Posted

pairs versus ipairs on numerically indexed tables is significantly slower.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...