Jump to content

Big doubt..


Recommended Posts

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

Link to comment

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.

Link to comment

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.

Link to comment

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...